How to make an endless For ONE in Python
Learn how to create an infinite loop in Python with an example. Explore the multiple ways to make an endless cycle to repeat tasks in your code.
Endless For Loop in Python
A for loop in Python is a type of loop that is used to iterate over a sequence of elements, meaning that it will run a block of code for each item in the sequence. An endless for loop is a type of for loop that will run forever, unless an external condition is used to terminate the loop.
An endless for loop is created by providing an empty sequence as the target for the loop. This is done by simply leaving the parenthesis empty, like so:
for item in ():
# Run code
This loop will run indefinitely, as there is no target for the for loop to iterate over. To end the loop, an external condition must be used. This external condition is typically another loop that will check for a condition, like so:
while True:
for item in ():
# Run code
if condition:
break
This loop will run the code block within the for loop, and check the condition within the while loop. If the condition is met then the while loop will terminate, and the for loop will terminate.
Endless for loops can be useful in certain cases, such as when a program needs to continually run a block of code until a certain condition is met. As long as an external condition is checked, an endless for loop can be safely used.