Python While Loop with Examples
Keep repeating until something changes: a countdown, a menu or a retry loop.
- How the while condition is checked
- Updating the variable that ends the loop
- break, continue and avoiding infinite loops
- 1
count > 0Check the condition - 2
print(count)Run the body - 3
count -= 1Move toward the end
Repeat while the condition is True
The problem
Some tasks repeat until something happens, and you cannot know in advance how many rounds that takes: ask for a password until it is correct, keep rolling a dice until you get a six, count down until zero. A for loop needs a known list; these tasks need a loop that checks a condition.
Think of it like this
A while loop is like stirring soup until it boils. You do not count stirs in advance. Before each stir you check: is it boiling yet? As long as the answer is no, you keep stirring. Something must change, or you would stir forever.
countdown = 3🍲 Start: the soup is coldwhile countdown > 0:❓ Check before each round: keep going?countdown -= 1🥄 Each round changes somethingprint("Go!")✅ Condition false: move onA while loop repeats its block as long as its condition is True, checking the condition again before every round.
Key points
while countdown > 0:checks the condition first; if it is already False, the block never runs.countdown -= 1changes the value every round, so the condition eventually becomes False.- Without that change the loop would run forever, and you would have to stop the program by hand.
- After the loop, the program continues with the next line, here
print("Go!").
When should you use it?
- Asking for input until it is valid, such as a menu choice or a password.
- Games and simulations that run until someone wins or time runs out.
- Repeating until a calculation is close enough, such as halving a number until it is below 1.
When not to use it
- Going through every item of a list: a
forloop is simpler and cannot loop forever. - Repeating a fixed number of times:
for _ in range(10):says that more clearly.
See how it works
Press Step to run the while loop one move at a time. The condition is checked before every pass, and the loop stops as soon as it is false.
Example code
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Go!")
Result of running the code
3
2
1
Go!
Code explanation
The counter changes during every iteration. Without that update, the condition would remain true and create an infinite loop.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Python while loop patterns
while count > 0: | Repeat as long as the condition is true |
count -= 1 | Update the variable the condition depends on |
while True: ... break | Loop until something inside decides to stop |
continue | Skip the rest of this pass and check the condition again |
while items: | Loop while a list still has items |
while ... else: | The else block runs when the condition becomes false (not after break) |
while (line := f.readline()): | Assign and test in one step (Python 3.8+) |
Common mistakes with Python while loops
Never updating the condition
If nothing inside the loop changes the condition, the loop runs forever.
count = 3
while count > 0:
print(count) # prints 3 forever
count = 3
while count > 0:
print(count)
count -= 1
continue before the update
continue jumps back to the condition, so an update placed after it is skipped and the loop can get stuck.
n = 0
while n < 5:
if n == 2:
continue # n stays 2 forever
print(n)
n += 1
n = 0
while n < 5:
n += 1
if n == 3:
continue
print(n) # 1, 2, 4, 5
Using while where a for loop is clearer
When you know the number of steps, a for loop with range() cannot forget the update.
i = 0
while i < 3:
print(i)
i += 1
for i in range(3):
print(i)
Frequently asked questions
What is the difference between a while loop and a for loop?
A for loop runs once per item in a sequence and stops by itself. A while loop runs as long as a condition is true, which suits cases where the number of steps is not known in advance, such as reading input until the user types quit.
How do I stop an infinite while loop?
Make sure the loop changes its condition, or use break when a stop condition is met. In a terminal, Ctrl+C interrupts a running program.
What does while True mean?
It starts a loop that only ends with break (or return). It is a common pattern for menus and input loops where the exit is decided inside the loop.
Does Python have a do-while loop?
No. Use while True: with the body first and if condition: break at the end, so the body always runs at least once.
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Halve Until One Count how many halvings bring a number down to 1. Easy
- Collatz Sequence Follow the halve-or-triple-and-add-one rule until reaching 1. Easy
- Sum of Digits Add up the decimal digits of a positive integer. Easy
- Sum of Odd Numbers Add every odd number up to a limit. Easy