Hanzy
Hanzy

Reputation: 414

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?

Upvotes: 0

Views: 6206

Answers (2)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

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.

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114230

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.

Upvotes: 1

Related Questions