0
0
PythonHow-ToBeginner · 3 min read

How to Create an Infinite Loop in Python: Simple Guide

To create an infinite loop in Python, use while True: followed by the code block you want to repeat endlessly. This loop runs forever until you stop it manually or use a break statement.
📐

Syntax

The basic syntax for an infinite loop in Python uses the while statement with the condition True. This means the loop condition is always true, so the loop never ends on its own.

  • while: starts the loop
  • True: condition that is always true
  • Indented block: code to repeat forever
python
while True:
    # code to repeat
    pass
💻

Example

This example prints numbers starting from 1 endlessly. It shows how the infinite loop keeps running until you stop the program manually (like pressing Ctrl+C).

python
count = 1
while True:
    print(count)
    count += 1
Output
1 2 3 4 5 6 7 8 9 10 ... (continues indefinitely)
⚠️

Common Pitfalls

Common mistakes include forgetting to add a way to stop the loop, which can freeze your program. Also, using while True without any break or exit condition means the loop never ends unless you force stop it.

Always plan how to exit an infinite loop safely.

python
wrong:
while True:
    print("Looping forever")

right:
count = 0
while True:
    print("Looping")
    count += 1
    if count == 5:
        break
Output
Looping Looping Looping Looping Looping
📊

Quick Reference

Remember these tips for infinite loops:

  • Use while True: for infinite loops
  • Include a break statement to exit when needed
  • Be careful to avoid freezing your program
  • Use Ctrl+C to stop running loops in the console

Key Takeaways

Use while True: to create an infinite loop in Python.
Always include a way to exit the loop, like a break statement.
Infinite loops run forever until stopped manually or by code.
Be cautious to avoid freezing your program with endless loops.
Use Ctrl+C in the console to stop an infinite loop during testing.