In the REPL, we can usually interrupt an infinite loop with a sigint, i.e. ctrl+c, and regain control in the interpreter.
>>> while True: pass
...
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>
But in this loop, the interrupt seems to be blocked and I have to kill the parent process to escape.
>>> *x, = itertools.repeat('x')
^C^C^C^C^C^C^C^C^\^\^\^\^\^Z^Z^Z^Z
Why is that?
The Python break statement immediately terminates a loop entirely.
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++) { ... }
As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.
A few types of Infinite Loop in Python include the While statement, the If statement, the Continue statement, and the Break statement.
The KeyboardInterrupt
is checked after each Python instruction. itertools.repeat
and the tuple generation is handled in C Code. The interrupt is handled afterwards, i.e. never.
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