Course Content
Python Loops Tutorial
Python Loops Tutorial
Infinite Loop
An infinite loop is a loop that never terminates because the condition controlling it never evaluates to False
. These loops can cause a program to hang or crash, so they should be avoided unless explicitly intended.
Example 1: An Unbreakable Truth
If a condition is always True
, the loop will run forever. For example, let's use a travel-related scenario:
Why is this Infinite?
- The condition
"Barcelona" in [...]
will always beTrue
because"Barcelona"
is present in the list. It's equal towhile True:
; - The loop continuously prints
"I found Barcelona!"
without any way to stop.
Example 2: A Stuck Counter
An improperly updated loop variable can also lead to an infinite loop. For example:
Why is this Infinite?
- The index
i
is never incremented, so the conditioni < len(travel_list)
is alwaysTrue
; - The loop keeps printing the first city (
"Monako"
) indefinitely.
To avoid infinite loops, ensure that the loop condition is designed to eventually evaluate to False
. This means the condition must be dynamic and change during the execution of the loop. Additionally, if you are using a variable (such as a counter) to control the loop, make sure it is incremented or updated properly within the loop to prevent the condition from remaining True
indefinitely.
1. What is the issue with the following code?
2. How can you modify this loop to prevent it from running forever?
Thanks for your feedback!