Consider the following snippet of Python code:
x = 14
for k in range(x):
x += 1
At the end of execution, x
is equal to 28.
My question: shouldn't this code loop forever? At each iteration, it checks if k
is less than x
. However, x
is incremented within the for loop, so it has a higher value for the next comparison.
We can create infinite loops in Python via the while statement. In a loop, the variable is evaluated and repeatedly updated (while the given condition is True). We can create an infinite loop in Python if we set the condition in a way that it always evaluates to True.
A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }
One of the most common infinite loops is when the condition of the while statement is set to true. Below is an example of code that will run forever. Another classic example will be of the for loop where the terminating condition is set to infinity.
To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever.
range(x)
is not a "command". It creates a range object one time, and the loop iterates over that. Changing x does not change all objects that were made using it.
>>> x = 2
>>> k = range(x)
>>> list(k)
[0, 1]
>>> x += 1
>>> list(k)
[0, 1]
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