Python Infinite While Loop
A Python while loop becomes infinite when its condition keeps evaluating to True and nothing inside the loop terminates it. An infinite loop can be intentional, such as a loop that waits for commands, or accidental, such as a loop whose control variable is never updated.
In this tutorial, we will create Python infinite while loops in several ways, see common bugs that cause them, and learn how to end or fix them with break, correct variable updates, and Ctrl+C when a program is already running.
How an Infinite While Loop Works in Python
A while loop checks its condition before each iteration. If the condition is True, Python runs the loop body and then checks the condition again. If that condition never becomes False, the loop keeps repeating unless execution is ended in another way, such as with a break statement, an exception, or an external interrupt.
while True:
# statements that repeat
if exit_condition:
break
The while True form is commonly used when the loop is intentionally open-ended but contains a clear condition that eventually executes break.
Flowchart – Python Infinite While Loop
Following is the flowchart of infinite while loop in Python.
As the condition is never going to be False, the control never comes out of the loop, and forms an Infinite Loop as shown in the above diagram.
Example 1 – Python Infinite While Loop with True for Condition
Firstly, we know that the condition in while statement has to always evaluate to True for it to become infinite Loop. Secondly, we also know that the condition evaluates to a boolean value. So, considering these two statements, we can provide the boolean value True, in place of condition, and the result is a infinite while loop.
Python Program
while True:
print("hello")
Output
hello
hello
hello
hello
Note: You will see the string hello print to the console infinitely. To interrupt the execution of the program, enter Ctrl+C from keyboard. This generates KeyboardInterrupt and the program will stop.
The four output lines shown above are only a sample. Without an exit condition, the program continues printing hello.
Example 2 – Python Infinite While Loop with Condition that is Always True
Instead of giving True boolean value for the condition, you can also give a condition that always evaluates to True. For example, the condition 1 == 1 is always true. No matter how many times the loop runs, the condition is always true and the while loop is running forever.
Python Program
while 1 == 1:
print("hello")
Output
hello
hello
hello
hello
This loop behaves like the first example because 1 == 1 never becomes false. For an intentional unconditional loop, while True communicates the intent more directly.
Example 3 – Python Infinite While Loop with No Update to Control Variables
These type of infinite while loops may result when you forget to update the variables participating in the condition.
In the following example, we have initialized variable i to 10. Typically, in the following example, one would decrement i to print hello 10 times. But, if we forget the decrement statement in the while body, i is never updated. This makes the loop an infinite while loop.
Python Program
i = 10
while i > 0:
print("hello")
Output
hello
hello
hello
hello
Here, i remains 10, so the condition i > 0 remains true. This is one of the most common causes of an accidental infinite while loop.
Example 4 – Python Infinite While Loop while working with Continue Statement
This also is a typical scenario where we use a continue statement in the while loop body, but forget to modify the control variable.
In the following example, we have initialized i to 10, and in the while loop we are decrementing i by one during each iteration. The condition is that i should be positive. When the while starts execution, and i is decrementing, and when i reaches 5, we have a continue statement. And we have not updated the control variable i. So, i is ever going to be 5. As a result, program control is never coming out of the while loop.
Python Program
i = 10
while i > 0:
if i == 5 :
continue
print("hello")
i -= 1
Output
hello
hello
hello
hello
hello
The loop prints hello for i values 10 through 6. When i becomes 5, continue skips the remaining statements in that iteration and starts the next condition check. Because i -= 1 is skipped, i stays 5 and the loop repeats without printing anything else.
Ending an Intentional Python Infinite While Loop with break
An infinite loop does not have to run until the program is interrupted. A common pattern is to use while True together with break. The loop remains open-ended, while a condition inside the loop decides when to stop it.
while True:
command = input("Enter a command (quit to stop): ")
if command == "quit":
break
print(f"Received: {command}")
print("Loop ended")
Each iteration reads a command. When the user enters quit, Python executes break and continues with the first statement after the loop. This is different from an accidental infinite loop because the exit path is explicit in the program.
How to Stop a Running Python Infinite While Loop with Ctrl+C
If a Python program is already stuck in an infinite loop in a terminal, pressing Ctrl+C normally interrupts the program and raises KeyboardInterrupt. In an IDE or notebook, you can also use that environment’s stop or interrupt control when available.
Ctrl+C is useful for stopping a loop during development, but it is not a replacement for correct loop logic. If the loop is supposed to finish on its own, fix the condition or add a deliberate exit path.
Fixing an Accidental Python Infinite While Loop
When a while loop should terminate, check every value used by its condition. At least one relevant value must change so that the condition can eventually become false, or the loop must reach a break statement.
For Example 3, decrementing i on every iteration fixes the loop:
i = 10
while i > 0:
print("hello")
i -= 1
Now i moves from 10 toward 0. After the tenth iteration, i > 0 becomes false and the loop ends.
Fixing a continue Statement That Prevents a Python while Loop from Ending
A continue statement skips the rest of the current loop body and immediately starts the next iteration. Therefore, a control-variable update placed after continue may never run on that path.
One fix is to update the control variable before executing continue:
i = 10
while i > 0:
if i == 5:
i -= 1
continue
print(i)
i -= 1
Output
10
9
8
7
6
4
3
2
1
When i is 5, the code changes it to 4 before continuing. The loop therefore keeps progressing toward its terminating condition.
Checking Python while Loop Conditions for Infinite-Loop Bugs
- Verify that variables used in the
whilecondition are updated on every path that should make progress. - Check whether a
continuestatement can skip an increment, decrement, input read, or state change. - For
while True, make sure an intentional exit path such asbreakis reachable when the stopping condition occurs. - When multiple conditions control the loop, confirm that the program can eventually change the values needed to make the complete condition false.
- If the program unexpectedly keeps running, inspect the condition values for successive iterations instead of only looking at the loop body.
Python Infinite While Loop Summary
In this Python Tutorial, we learned how to write an Infinite While Loop, in some of the many possible ways, with the help of example programs.
An intentional infinite loop is commonly written as while True and given a clear exit path with break. Accidental infinite loops usually happen because the loop condition never changes, a control variable is not updated, or continue skips the update. During development, Ctrl+C can interrupt a running loop in a terminal, but the lasting fix is to correct the loop’s termination logic.
TutorialKart.com