0
0
PythonHow-ToBeginner · 3 min read

How to Exit a Loop in Python: Simple Guide with Examples

In Python, you can exit a loop early using the break statement. When break runs inside a loop, it immediately stops the loop and moves on to the next part of the program.
📐

Syntax

The break statement is used inside loops to stop the loop immediately. It works with both for and while loops.

Here is the basic syntax:

  • for item in iterable: - starts a loop over items
  • while condition: - starts a loop while condition is true
  • break - stops the loop immediately
python
for item in range(5):
    if item == 3:
        break
    print(item)
Output
0 1 2
💻

Example

This example shows a while loop that counts from 1 upwards. When the count reaches 5, the break statement stops the loop.

python
count = 1
while True:
    print(count)
    if count == 5:
        break
    count += 1
Output
1 2 3 4 5
⚠️

Common Pitfalls

One common mistake is to forget the break statement inside the loop, which causes the loop to run forever if the exit condition is never met.

Another mistake is placing break outside the loop or in the wrong indentation, which causes a syntax error or unexpected behavior.

python
count = 1
while True:
    print(count)
    # Missing break causes infinite loop
    # if count == 5:
    #     break
    count += 1

# Correct usage:
count = 1
while True:
    print(count)
    if count == 5:
        break
    count += 1
Output
1 2 3 4 5
📊

Quick Reference

Use break to exit loops early when a condition is met. It works with both for and while loops. Remember to place it inside the loop body and ensure your exit condition is reachable to avoid infinite loops.

Key Takeaways

Use break inside loops to exit immediately when needed.
Place break correctly inside the loop body to avoid syntax errors.
Always ensure your loop has a reachable exit condition to prevent infinite loops.
break works with both for and while loops.
Without break, loops run until their natural end or condition fails.