简体   繁体   中英

Change range start in Python 'for loop' for each iteration

I'm a novice and learning python (using 2.7). I'm attempting some simple scripts to test how python handles different types of loops.

My question is: can python change the starting point of the "range" function on each iteration if the start point is assigned to a variable? Here is an example of my code:

def build(n, period):
    n2 = n
    for digit in range(int(n2), 20):
        print "At the top i is %d" % n
        digit += period
        numbers.append(digit)

        print "Numbers now:", numbers
        print "At the bottom i is %d" % digit

        print "The Numbers:"
        n2 += period

        for num in numbers:
            print num


key = raw_input("Press 1 to call function \"build\", press any other key to quit.")
if key == "1":
    i = raw_input("What integer is our start value?")
    amt = raw_input("What is the common difference?")
    numbers = [int(i)]
    build(int(i),int(amt))

else:
    quit()

I tried to use a second local variable 'n2' inside the function so I could keep the initial value of 'n' constant and then redefine the range for each iteration. The very first number in the appended list moves by the common difference but after that it always steps by +1 integer. I can easily make this happen with a 'while' loop but curious if a 'for' loop can be used to accomplish this?

range creates a fixed list the moment you call that function at the beginning of your for loop. You can think of the top of the for loop as assigning n2 to the next element of that list no matter what you do inside the loop. If you want to change the period of the range, use the third argument:

range(n, 20, period)

will move in steps of size period through the range instead of steps of size one.

It won't work in a way you expect. Expression range(int(n2), 20) gets evaluated only one time in the beginning of for-loop. You can't change the scope of a for-loop that way.

What you can modify is a step parameter in range function, but it does not change your starting point - it only defines what is the next element in the iteration process.

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