Is it possible to get an infinite loop in for
loop?
My guess is that there can be an infinite for loop in Python. I'd like to know this for future references.
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++) { ... }
Infinite While Loop in Pythona = 1 while a==1: b = input(“what's your name?”) print(“Hi”, b, “, Welcome to Intellipaat!”) If we run the above code block, it will execute an infinite loop that will ask for our names again and again. The loop won't break until we press 'Ctrl+C'.
You can use the second argument of iter()
, to call a function repeatedly until its return value matches that argument. This would loop forever as 1 will never be equal to 0 (which is the return value of int()
):
for _ in iter(int, 1): pass
If you wanted an infinite loop using numbers that are incrementing you could use itertools.count
:
from itertools import count for i in count(0): ....
The quintessential example of an infinite loop in Python is:
while True: pass
To apply this to a for loop, use a generator (simplest form):
def infinity(): while True: yield
This can be used as follows:
for _ in infinity(): pass
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