Troas
Troas

Reputation: 1227

Assign new value to variable used in while loop comparison after loop is entered

I was wondering if anything speaks against assigning a new value to a variable that is used in a comparison in a while loop after the while loop has been entered. A dummy example:

i = 0
target = 10
while i < target:
    print i
    if i == 9:
        target = 20
    i = i + 1

Upvotes: 2

Views: 4142

Answers (1)

Bhavana
Bhavana

Reputation: 311

No, nothing stops you from doing that. Your example in and of itself is a proof.

Although, a better practice would be to use a while True: loop and break on a condition. Since your loop condition itself is prone to change, it's not really an invariant condition at all. Hence, I suggest you do:

i = 0
target = 10
while True:
    print i
    i = i + 1

    # If i hits 9 at any point, change target
    if i == 9:
        target = 20

    # If i ever hits the target, break
    if i >= target:
        break

Upvotes: 8

Related Questions