简体   繁体   中英

can't find a solution to the problem in this function def interval()

I'm learning python right now and following this book "Beginning Python" I've got stuck at this example:

def interval(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    result = []
    i = start
    while i < stop:
        result.append(i)
        i += stop
    return result

If I call this function let say interval(10) it doesn't print anything. I code in PyCharm Python 3.9

You just had a typo in your while loop when incrementing your step, ie i += stop . Instead of stop use step.

def interval(start, stop=None, step=1):
if stop is None:
    start, stop = 0, start
result = []
i = start
while i < stop:
    result.append(i)
    i += step
return result

print(interval(10))

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM