I am not sure why python would show this behavior:
for x in range(5):
print "Before: ",x
if x<3:
x-=1
print "After: ",x
I get the output as:
Before: 0
After: -1
Before: 1
After: 0
Before: 2
After: 1
Before: 3
After: 3
Before: 4
After: 4
I was not expecting it to change the value of x to 1, after I reduce it to -1 in the first iteration. Alternatively, is there a way to achieve the desired behavior when I want to alter the value of range variable?
Thanks.
A for loop in Python doesn't care about the current value of x (unlike most C-like languages) when it starts the next iteration; it just remembers the current position in the range and assigns the next value. In order to be able to manipulate the loop variable, you need to use a while loop, which doesn't exert any control over any variables (it just evaluates the condition you give it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With