A Python while loop repeats a block of code for as long as its condition is true. Python checks the condition before every pass and leaves the loop as soon as the condition is false.
count = 1
while count <= 3:
print(count)
count += 1
print("Done")This prints 1, 2, 3, and then Done. When count reaches 4, the condition count <= 3 is false, so Python skips the block and continues with the line after the loop.
The syntax
while condition:
# block to repeatA working while loop almost always has three parts:
- A starting value set before the loop (
count = 1). - A condition that is checked before each pass (
count <= 3). - An update inside the block that moves towards ending the loop (
count += 1).
If the condition is false the very first time, the block never runs at all.
When to use while instead of for
Use a for loop when you are going through a collection or know the number of repetitions. Use a while loop when you cannot know how many passes you need:
- Keep asking until the user enters valid input.
- Keep reading until a file or network stream is finished.
- Run a game or menu until the player quits.
- Repeat a calculation until the result is close enough.
# How many years until savings double at 5% interest?
balance = 1000
years = 0
while balance < 2000:
balance *= 1.05
years += 1
print(years) # 15There is no list to loop over here. The loop simply runs until the goal is reached.
Avoid infinite loops
If nothing inside the block changes the condition, the loop never ends:
count = 1
while count <= 3:
print(count)
# count += 1 is missing, so this prints 1 foreverTo stop a program that is stuck in a loop, click in the terminal and press Ctrl+C. Python stops with a KeyboardInterrupt message.
When a loop will not stop, check three things: that the update line exists, that it is indented inside the loop, and that it moves the variable in the right direction.
while True with break
Sometimes the natural place to decide whether to stop is in the middle of the block. The usual pattern is an intentionally endless loop with a break:
while True:
command = input("Type a command (or quit): ")
if command == "quit":
break
print("You typed:", command)
print("Goodbye")while True never becomes false, so the only way out is the break statement. This avoids asking for input in two places, once before the loop and once inside it.
Python has no do while loop. while True with a break at the end of the block is how you write a loop that must run at least once.
Validate user input
A while loop is the standard way to ask again until the input is acceptable:
while True:
answer = input("Enter your age: ")
if answer.isdigit() and int(answer) > 0:
age = int(answer)
break
print("Please enter a whole number above zero.")
print("Your age is", age)str.isdigit() checks that the text contains only digits, so the conversion with int() cannot fail. More on reading input is in getting user input in Python.
Loop until a collection is empty
An empty list counts as false, so a list can be the condition itself:
queue = ["email", "report", "backup"]
while queue:
task = queue.pop(0)
print("Processing", task)
print("All tasks done")Each pass removes the first task. When the list is empty, the loop ends.
The else clause
Like a for loop, a while loop can have an else block. It runs when the condition becomes false, but not when the loop is left with break:
attempts = 0
while attempts < 3:
guess = input("Password: ")
if guess == "open sesame":
print("Access granted.")
break
attempts += 1
else:
print("Too many attempts.")Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| No update inside the loop | Infinite loop | Change the condition variable in the block |
| Update line not indented | Infinite loop | Indent it to the level of the block |
Using < where <= is needed | The loop runs one time too few | Trace the first and last pass by hand |
Comparing input() text with a number | The condition is never true | Convert with int() or float() first |
Using while to walk a list by index | Extra code and off-by-one bugs | Use a for loop |
Rune AI
Key Insights
- A while loop repeats its block for as long as the condition is true and checks the condition before every pass.
- Most while loops need a starting value, a condition, and an update that moves towards ending the loop.
- A loop with no update never ends; press Ctrl+C to stop it.
- Use while True with break when the exit decision belongs in the middle of the block.
- Python has no do while loop; while True with break covers that case.
- Prefer a for loop when you are going through a collection.
Frequently Asked Questions
What is a while loop in Python?
What is the difference between for and while in Python?
How do I stop a while loop in Python?
Does Python have a do while loop?
What does while True mean in Python?
Conclusion
Use a while loop when repetition depends on a condition rather than on a collection. Set a starting value, check a condition, and make sure something in the block moves towards ending the loop. For input and menus, while True with a break is the clearest pattern.
More in this topic
Nested Loops in Python
A nested loop is a loop inside another loop. See exactly what order the lines run in, how to work with grids and nested lists, and how to break out of both loops.
Python break, continue, and pass Explained
break exits a loop, continue skips to the next pass, and pass does nothing at all. See how each one works in for and while loops, and when to use them.
Common Python Mistakes Beginners Make
Twelve mistakes nearly every Python beginner makes, with the exact error message each one produces and the fix. Learn to recognise them and you will debug much faster.