Reading history

Python while Loop: break, continue and while-else

4 min read 2 views

Learn the Python while loop: how the condition is checked, avoiding infinite loops, the while True and break pattern, and while-else.

A while loop keeps running as long as its condition is true. Use it when you do not know in advance how many times to repeat: keep asking until the password is right, keep reading until the data ends, keep dividing until a number reaches zero. This lesson covers the basic loop, infinite loops with break, and while ... else.

In this lesson you will learn

  • How a while loop checks its condition
  • How to avoid accidental infinite loops
  • The while True + break pattern
  • When the else block of a while loop runs

How a while Loop Works

Python checks the condition before every pass. If it is true, the body runs and Python checks again. If it is false, the loop ends and the program continues below it.

count = 3
while count > 0:
    print("Countdown:", count)
    count -= 1
print("Lift off!")

# digits of a number
n = 40721
total = 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum of digits:", total)

Output

Countdown: 3
Countdown: 2
Countdown: 1
Lift off!
Sum of digits: 14

The second loop adds up the digits of 40721. n % 10 takes the last digit and n //= 10 removes it, so the loop ends once every digit has been used: 4 + 0 + 7 + 2 + 1 = 14. Nobody had to count the digits first, and that is exactly the kind of job a while loop is for.

Always change something the condition depends on

If the body never changes count, then count > 0 stays true forever and the program hangs. Press Ctrl+C in the terminal to stop a runaway loop.

while True, break and else

# Simulated user input so the example runs on its own
attempts = iter(["1234", "0000", "7391"])
PIN = "7391"

tries = 0
while True:
    guess = next(attempts)
    tries += 1
    if guess == PIN:
        print(f"Unlocked after {tries} tries")
        break
    print("Wrong PIN:", guess)

# while ... else runs only if the loop ends without break
balance = 100
while balance >= 30:
    balance -= 30
    print("Bought a coffee, balance:", balance)
else:
    print("Not enough money for another coffee")

Output

Wrong PIN: 1234
Wrong PIN: 0000
Unlocked after 3 tries
Bought a coffee, balance: 70
Bought a coffee, balance: 40
Bought a coffee, balance: 10
Not enough money for another coffee
  • while True loops forever on purpose; a break inside provides the exit. This is the usual shape for menus and input checks, where the exit test is easiest to write in the middle of the loop.
  • Here the “user input” comes from a fixed list via next(), so the example runs without typing. In a real program you would use input("PIN: ").
  • while ... else: the else block runs when the condition becomes false. It does not run if the loop ended with break.

for or while?

UseWhen
forYou are going through a known collection or a fixed count.
whileYou repeat until something happens and cannot know the count in advance.

Common Mistakes

  1. Forgetting to update the loop variable, which creates an infinite loop.
  2. Off-by-one conditions. while i < 10 stops at 9; while i <= 10 includes 10.
  3. Using while to walk a list by index. A for loop is shorter and safer.
  4. Expecting do ... while. Python has none; use while True with a break at the end of the body.

Practice Exercises

Exercise 1. Starting from 1, keep doubling a number until it is larger than 1000. Print the final value.

Show answer
n = 1
while n <= 1000:
    n *= 2
print(n)   # 1024

Exercise 2. Reverse the digits of 1234 using a while loop.

Show answer
n, rev = 1234, 0
while n > 0:
    rev = rev * 10 + n % 10
    n //= 10
print(rev)   # 4321

Frequently Asked Questions

How do I stop an infinite loop?

Press Ctrl+C in the terminal. In code, make sure the condition can become false or that a break is reachable.

Can I use continue in a while loop?

Yes. It jumps straight back to the condition check. Make sure the loop variable is updated before the continue, or the loop may never end.

Summary

  • while condition: repeats while the condition is true.
  • Change the condition’s variables inside the loop to avoid hanging.
  • while True + break handles “repeat until” logic.
  • The else block runs only if no break happened.

Next: package reusable code with Python Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *