简体   繁体   中英

How does a for loop know to increment

When defining a Fibonacci sequence the following code was used:

def fibonacci(n):
    current=0
    after=1
    for i in range(1,n):
        current,after=after,current+after
    return after

How does the for loop know to increment by one every time we pass through? I tried using a while loop while e<=n: and it returned an error as I hadn't defined e .

A for loop in python iterates through items or generators. In your example, range(1,n) will return a list of elements between [1, n) in python2, or a generator that will yield the same items in python3.

Essentially, a for loop can iterate any kind of iterables :

for item in [1, 6, 8, 9]:
    print(item)

It will print 1, 6, 8 and 9.

Using range , there is a 3rd optional parameter which allows you to specify the increment:

range(1, 10, 1)  # The defaut [1 .. 9] numbers
range(1, 10, 2)  # From 1 until 9 with 2 of increment

for loop does not increment, instead it iterates

The for loop does not increment, instead it is asking so called iterable to provide values to work with.

In your example, the iterable is range(1,n) .

In Python 2.x, the range(1, n) creates a list of values and the for loop is only asking the list to provide next value in each run, until the list gets exhausted from values.

In Python 3.x the range(1, n) is optimized and returns special iterable type <range> , which when asked by for loop to provide next value provide it.

默认情况下,如果您未指定步长,即对于范围(开始,停止,步长)中的i,则增量将被视为1,否则就是您指定的步长。

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