Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Infinite Loop | The while Loop
Python Loops Tutorial
course content

Course Content

Python Loops Tutorial

Python Loops Tutorial

1. The for Loop
2. The while Loop
3. Nested Loops

book
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 be True because "Barcelona" is present in the list. It's equal to while 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 condition i < len(travel_list) is always True;
  • 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?
What is the issue with the following code?

What is the issue with the following code?

Select a few correct answers

How can you modify this loop to prevent it from running forever?

How can you modify this loop to prevent it from running forever?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt