Loops are generally aimed to repeat a particular set of statements until a given condition is fulfilled. However, there may be a case when a condition is never fulfilled, as a result of which statements are executed again and again. We call this “Infinite looping”. Hence, in other words, Infinite loops are the loops that run indefinitely until the program is terminated.
Simple example of Infinite loop:
while True:
print("True")
Above example will run infinite times as it does not have any breaking condition.
Let’s dive in more :
Consider the following Python code with while loop :
i=1
while i < 11:
print(i, end=' ')
i += 1
Above code will print counting from 1 to 10. It will terminate when value of i reaches to 11. However, if we don’t write the last statement (i=i+1), then, for every iteration, i will be 1. Hence, loop will never terminate and will result in an infinite loop.
#Do_One_Thing : Take the below code snippet and try to execute this program on your system.
i=1
while(i < 11):
print("There is no escape !")
Just like Infinite while loops, we can also have Infinite for loops as well. Consider the example below
l = [2]
for i in l:
l.append(i)
print("running") # keep printing "running" on every iteration
That’s all you need to know about Infinite looping in Python. See you in the next lecture.
The simplest infinite loop I can think:
while True:
print(“Infinite Loop”)