>>> k = 8
>>> for i in range(k):
print i
k -= 3
print k
Above the is the code which prints numbers from <
The expression range(k)
is evaluated just once, not on every iteration. You can't set k
and expect the range(k)
result to change, no. From the for statement documentation:
The expression list is evaluated once; it should yield an iterable object.
You can use a while
loop instead:
i = 0
k = 8
while i < k:
print i
i += 1
k -= 3
A while
loop does re-evaluate the test each iteration. Referencing the while statement documentation:
This repeatedly tests the expression and, if it is true, executes the first suite