>>> k = 8
>>> for i in range(k):
print i
k -= 3
print k
Above the is the code which prints numbers from 0-7
if I use just print i
in the for loop.
I want to understand the above code how it is working, and is there any way we can update the value of variable used in range(variable)
so it iterates differently.
Also why it always iterates up to the initial k
value, why the value doesn't updated.
I know it's a silly question, but all ideas and comments are welcome.
If you do want to change k and affect the loop you need to make sure you are iterating over mutable object. For example:
Or alternatively:
Both will result with
The expression
range(k)
is evaluated just once, not on every iteration. You can't setk
and expect therange(k)
result to change, no. From thefor
statement documentation:You can use a
while
loop instead:A
while
loop does re-evaluate the test each iteration. Referencing thewhile
statement documentation:You can't change the range after it's been generated. In Python 2,
range(k)
will make a list of integers from 0 to k, like this:[0, 1, 2, 3, 4, 5, 6, 7]
. Changingk
after the list has been made will do nothing.If you want to change the number to iterate to, you could use a while loop, like this: