0

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?

1
  • you can use a while loop if you are looking for other loops - while n2 < 20: n2+= period. Also you will have to pass the numbers array to the function. Else you can call it as global variable. Commented Aug 1, 2017 at 17:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

How will you get an index out of bounds?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.