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
whileloop checks its condition - How to avoid accidental infinite loops
- The
while True+breakpattern - When the
elseblock 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 Trueloops forever on purpose; abreakinside 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 useinput("PIN: "). while ... else: theelseblock runs when the condition becomes false. It does not run if the loop ended withbreak.
for or while?
| Use | When |
|---|---|
for | You are going through a known collection or a fixed count. |
while | You repeat until something happens and cannot know the count in advance. |
Common Mistakes
- Forgetting to update the loop variable, which creates an infinite loop.
- Off-by-one conditions.
while i < 10stops at 9;while i <= 10includes 10. - Using
whileto walk a list by index. Aforloop is shorter and safer. - Expecting
do ... while. Python has none; usewhile Truewith abreakat 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+breakhandles “repeat until” logic.- The
elseblock runs only if nobreakhappened.
Next: package reusable code with Python Functions.
