Why is the following simple loop not saving the value of i
at the end of the loop?
for i in range( 1, 10 ):
print i
i = i + 3
The above prints:
1
2
3
4
5
6
7
8
9
But it should print:
1
4
7
for
sets i
each iteration, to the next value from the object being iterated over. Whatever you set i
to in the loop is ignored at that point.
From the for
statement documentation:
The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.
i
is the target list here, so it is assigned each value from the range(1, 10)
object. Setting i
to something else later on doesn't change what the range(1, 10)
expression produced.
If you want to produce a loop where you alter i
, use a while
loop instead; it re-tests the condition each time through:
i = 1
while i < 10:
print i
i += 3
but it'll be easier to just use a range()
with a step, producing the values up front:
for i in range(1, 10, 3):
print i
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