2

How do I change the higher limit of a python for loop at runtime?

The code,

from random import randint

lower_limit = 0
higher_limit = 200
step_size = 5

for i in range(lower_limit, higher_limit, step_size):
    # do something

    higher_limit = higher_limit + randint(0, 5)

The code runs till the first higher limit and doesn't care about the declared one, What can be done to make this work?

3 Answers 3

4

you need to use while:

from random import randint

lower_limit = 0
higher_limit = 200
step_size = 5

while i <higher_limit:
    # do something

    higher_limit = higher_limit + randint(0, 5)
    i += 5
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I haven't noticed that. I changed it :)
2

You can't modify a range once it is created. I think it would be easier for you to restructure your logic and replace range with while:

lower_limit = 0
higher_limit = 200
step_size = 5
i = 0

while lower_limit <= i < higher_limit:
    # do something

    i = i + step_size

    higher_limit = higher_limit + randint(0, 5)

Comments

-1

maybe you can define your own version of range (simplified):

from random import randint

def higher_range(start, upto, step, inc):
    i = start
    while i < upto:
        yield i
        i += step
        upto += randint(0, inc)

for j in higher_range(0, 10, 5, 5):
    print j

Obviously, there is not guarantee it will terminate any time soon...

Comments

Your Answer

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