while Loops
Computers are good at doing the same thing many times without getting bored. A loop repeats a block of code. Python has two kinds: the for loop, which goes through a collection of items, and the while loop, which keeps going as long as a condition stays true.
In this lesson you will write while loops that stop at the right moment, exit early with break, skip a round with continue, use the unusual else clause, and learn how to escape from a loop that never ends.
The while loop
A while loop looks like an if statement: a condition, a colon and an indented block. The difference is that after the block runs, Python goes back and checks the condition again. It repeats until the condition is false.
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1
print("Lift off!")5 4 3 2 1 Lift off!
Each pass through the block is called an iteration. Trace it: countdown starts at 5, the condition is true, Python prints 5 and subtracts 1. This repeats until countdown is 0, the condition 0 > 0 is false, and the program continues after the loop.
Repeat until a goal is reached
while is the right loop when you do not know in advance how many rounds you need. How many years does it take for a fixed deposit to double at 7% interest a year?
amount = 10000
target = 20000
rate = 0.07
years = 0
while amount < target:
amount = amount * (1 + rate)
years += 1
print(f"It takes {years} years to reach ₹{amount:,.2f}")It takes 11 years to reach ₹21,048.52
Nobody told the loop to run 11 times. It simply kept adding interest until the amount crossed the target.
Infinite loops
If the condition never becomes false, the loop never ends. This is an infinite loop, and it is the most common while loop bug. It usually happens when you forget to update the variable in the condition:
count = 1
while count <= 5:
print("Hello")
# forgot: count += 1This prints "Hello" forever. If it happens in a terminal, press Ctrl+C to stop the program. In the browser editor, stop or reload the page. Before you run a while loop, ask yourself: "what changes inside the loop, and will it make the condition false?"
break and continue
Two statements change the normal flow of a loop:
breakleaves the loop immediately, even if the condition is still true.continueskips the rest of the current iteration and jumps back to the condition.
A common pattern is while True: with a break inside. The loop is written to run forever, and break decides when it stops:
correct_pin = "4321"
attempts = ["1111", "", "4321", "9999"]
tries = 0
while True:
pin = attempts[tries]
tries += 1
if pin == "":
print("Empty PIN, please type again")
continue
if pin == correct_pin:
print(f"PIN accepted after {tries} tries")
break
print("Wrong PIN")Wrong PIN Empty PIN, please type again PIN accepted after 3 tries
The list attempts stands in for what a user would type. When the PIN is empty, continue skips the checks and goes straight to the next attempt. When it is correct, break ends the loop, so the fourth attempt is never read.
The else clause on a loop
A while loop can have an else block. It runs when the loop ends normally, because the condition became false. It does not run if the loop was stopped by break. That makes it a neat way to say "the search found nothing".
number = 97
divisor = 2
while divisor * divisor <= number:
if number % divisor == 0:
print(number, "is not prime; it divides by", divisor)
break
divisor += 1
else:
print(number, "is prime")97 is prime
No divisor was found, so the loop ended normally and the else block ran. Change number to 91 and the break runs instead (91 is 7 times 13), so else is skipped. Many programmers find loop else surprising; if it confuses your team, a Boolean variable such as found = False does the same job.
Loops that empty a collection
Because an empty list is falsy, while items: means "while there is anything left". This is perfect for working through a queue:
orders = ["masala dosa", "idli", "filter coffee"]
while orders:
current = orders.pop(0)
print(f"Serving {current}, {len(orders)} left")Serving masala dosa, 2 left Serving idli, 1 left Serving filter coffee, 0 left
pop(0) removes and returns the first item, which you will see again in Lists. The list shrinks each time, so the loop is sure to end.
You will also meet the walrus operator from Booleans & Operators in while loops. This common pattern keeps asking until the user types "quit":
while (command := input("> ")) != "quit":
print("You typed", command)while or for?
Use a for loop when you are going through items you already have: every name in a list, every line in a file, every number from 1 to 10. Use a while loop when you repeat until something happens: a target is reached, a user quits, a correct answer arrives. You will learn for loops in for Loops.
Common mistakes
- Forgetting to update the condition variable. The loop never ends. Make sure something inside the loop moves it towards false.
- Off-by-one errors.
while count < 5withcountstarting at 1 runs 4 times, not 5. Trace the first and last iteration by hand. - Using
whilewith an index to walk through a list. It works, but aforloop does it with less code and no risk of an infinite loop. - Expecting
elseto run afterbreak. The loop'selseruns only when the loop ends withoutbreak.
Key points
while condition:repeats its block as long as the condition is true.- Something inside the loop must change so that the condition eventually becomes false.
- Press Ctrl+C in a terminal to stop an infinite loop.
breakleaves the loop now;continuejumps to the next iteration.- A loop's
elseblock runs only if the loop finished withoutbreak. while items:loops until a list is empty; useforto visit items you already have.
Exercise
Isha saves ₹500 in her first month, and each month after that she saves ₹100 more than the month before (₹600, then ₹700, and so on). Use a while loop to find how many months it takes her to save at least ₹10,000 in total. Print the number of months and the total saved.
Show solution
saved = 0
monthly = 500
months = 0
while saved < 10000:
saved += monthly
monthly += 100
months += 1
print(f"{months} months, total saved ₹{saved:,}")11 months, total saved ₹11,000
The loop keeps adding a growing monthly amount until the total reaches the goal. Three variables change on each pass: the total, the next month's amount and the month counter.
Quick Quiz
1. When does a while loop stop?
The condition is checked before each iteration; break can also end the loop early.
2. What does continue do inside a loop?
continue jumps straight to the next check of the condition.
3. When does the else block of a while loop run?
If break ends the loop, else is skipped; otherwise it runs once the condition becomes false.
4. Which key combination stops a program stuck in an infinite loop in a terminal?
Ctrl+C interrupts the running Python program.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
