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
range(1,10,3)do-test-repeat for loop of other languages. In java, I think, there is for each loop, which is more similar to the python loop; perhaps such naming makes it a little more clear how that loop behaves, right ?for x in iterable: and foreach (x in iterable) { is almost identical, from a comprehension standpoint. The only issue here is that i in range(1,10) is actually a boolean expression when not used within the context of a for loop. Therefore someone might get confused with a while loop. For loops in many languages are a bit of a misnoma IMO. They're really while loops but with some syntactic sugar on.for i in range(1,10) and while i in range(1,10) here; they do two very different things, even though, to a beginning programmer, the difference may seem subtle and arbitrary.
forworks, but the question itself has a definite answer. If you think this is a poor/useless question downvote.forloop, where changing the iteration variable within the body also changes the iterations