0
0
PythonHow-ToBeginner · 3 min read

How to Use while True Loop in Python: Simple Guide

In Python, while True creates an infinite loop that runs until you stop it manually or use a break statement inside the loop. This is useful for repeating actions until a condition inside the loop is met.
📐

Syntax

The while True loop runs endlessly because the condition True is always true. Inside the loop, you usually add a break statement to stop the loop when needed.

  • while True: starts the infinite loop
  • code block: the repeated actions inside the loop
  • break: stops the loop when a condition is met
python
while True:
    # repeated code here
    if some_condition:
        break
💻

Example

This example asks the user to enter a number repeatedly until they type 'exit'. It shows how while True keeps the program running and break stops it.

python
while True:
    user_input = input("Enter a number or 'exit' to stop: ")
    if user_input.lower() == 'exit':
        print("Loop stopped.")
        break
    print(f"You entered: {user_input}")
Output
Enter a number or 'exit' to stop: 5 You entered: 5 Enter a number or 'exit' to stop: 10 You entered: 10 Enter a number or 'exit' to stop: exit Loop stopped.
⚠️

Common Pitfalls

One common mistake is forgetting the break statement, which causes the loop to run forever and freeze the program. Another is placing break incorrectly so it never runs.

Always ensure your loop has a clear exit condition inside.

python
while True:
    print("This will print forever!")

# Correct way:
while True:
    answer = input("Type 'stop' to end: ")
    if answer == 'stop':
        break
📊

Quick Reference

Use while True for loops that need to run until a specific event happens inside the loop. Always pair it with break to avoid infinite loops.

  • while True: start infinite loop
  • break: exit loop
  • continue: skip to next loop cycle

Key Takeaways

Use while True to create loops that run until you manually stop them.
Always include a break statement inside to avoid infinite loops.
Place the break where the exit condition is checked.
Infinite loops are useful for waiting on user input or events.
Test loops carefully to prevent freezing your program.