for and range(..) object range(..)
If you write for i in range(..): Python does not translate this into something like for(int i = 0; i < n; i++) (in the C programming language family).
In addition, the range object is constructed once before the for loop. The range(..) object does not know which variables were used to create it. After building, the range is fixed.
It sees range(..) as an iterable object, and each iteration takes the next element, which has an iterative output. So, regardless of whether the variable is set or not in the for loop, the effect does not work for the next iteration.
In python-2.x , range(..) not a specific object, but a call to build a list. Therefore, if you call range(10) (without a for loop), you get [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .
Why is this not working?
So why the examples do not work?
a=5 for i in range(1,a): print(i) a=a+1
Here we build range(..) once. After that, the variables on the basis of which it was constructed can change, since the range(..) object will change more. Thus, incrementing a does not mean that the range object will become larger.
for i in range(1,4): print(i) i=i-1
The for loop takes the next iteration element each time. Therefore, if we first collected 1 from the range loop, the next iteration, we collect 2 . This is independent of the value of i .
for i in range(1,4): print(i) i=1
For the same reason: for does not take into account the previous value of i . It only extracts the next element iterable (here range(..) gives). Since range(..) fixed, it simply passes the for loop to the next element.
Endless loop emulation
So, we need to build iterability that preserves inferior elements. The way to do this is itertools.count :
from itertools import count for i in count():
Or, if you are not interested in any value, we can use repeat :
from itertools import repeat for _ in repeat(None):