Try Again with a while Loop
So far every line of a program has run at most once: Python reads the file from top to bottom, and an if decides whether a block runs or is skipped. Many tasks need the same steps again, such as asking a question until the answer is right, or doing something exactly three times. A loop is a block of code that Python runs again and again. In Python, the simplest loop is the while loop: it repeats a block as long as a condition stays True.
Repeating a block while a condition is True
A while loop looks like an if statement: the word while, a condition, a colon, and an indented block below it. The condition is any expression that gives True or False, such as a comparison. The difference is what happens after the block. An if runs its block once and moves on. A while goes back to the top and tests its condition again. As long as the test gives True, the block runs once more. The first time the test gives False, the loop ends and Python goes on with the first line after the block.
Here is a loop that keeps asking until the answer is right:
answer = input("What is 3 + 4? ")
while answer.strip() != "7":
answer = input("Not quite. Try again: ")
print("Correct!")The first line asks once. Then the while line compares the tidied answer with "7". If they differ, the condition is True, so the indented line runs and asks again, putting the new reply into answer. Then Python is back at the while line, testing the new answer. When the reply is finally 7, the condition gives False, the block is skipped, and the program prints Correct!. One round of the loop, one run of its block, is often called an iteration.
Two details of this cycle matter for predicting what a loop does. First, the condition is tested before each round, only there. Python never checks it halfway through the block, so once a round has started, the whole block finishes. Second, the very first test may already be False. If the user types 7 at the first prompt, the block runs zero times and the program goes straight to Correct!.
- Lines before the loop
- Test the condition answer.strip() != "7"
- Run the block once ask again
- First line after the loop print("Correct!")
- Lines before the loop to Test the condition
- Test the condition to Run the block once: True
- Run the block once to Test the condition: back to the test
- Test the condition to First line after the loop: False
True or false?
The block of a while loop always runs at least once.
False. The condition is tested before the first round too. If it is already False, the block runs zero times.
If the condition becomes False in the middle of the block, the rest of that block still runs.
True. Python tests the condition only at the top, before each round, so a round that has started always finishes.
Counting rounds with a counter
A loop often has to run a set number of times. For that we use a counter: a variable that holds a number and is updated in every round, usually by adding one. Three lines work together: one before the loop gives the counter its start value, the condition compares it with a limit, and a line inside the block moves it forward.
count = 0
while count < 3:
print(f"Round {count}")
count = count + 1
print(f"After the loop, count is {count}")The line count = count + 1 reads as an instruction, not as maths: take the value count has now, add one, and store the result back in count. Tracing the loop by hand, one test at a time, shows exactly what happens:
| Test number | count at the test | count < 3 | What happens |
|---|---|---|---|
| 1 | 0 | True | prints Round 0, count becomes 1 |
| 2 | 1 | True | prints Round 1, count becomes 2 |
| 3 | 2 | True | prints Round 2, count becomes 3 |
| 4 | 3 | False | loop ends |
Round 0
Round 1
Round 2
After the loop, count is 3The block ran three times, but the condition was tested four times: the fourth test is the one that ended the loop. That is why the counter holds 3 after the loop, not 2. It keeps the first value that made the test False, because the loop only stops at a test.
This gives a quick way to predict a counting loop. Write n for the limit. When the counter starts at 0, goes up by 1 each round and is tested with count < n, the block runs n times and the counter ends at n. Small changes to the loop above shift the result. The test count <= 3 also lets 3 through, so the block runs four times and the counter ends at 4. A start value of 5 makes its first test, 5 < 3, give False, so the block runs zero times and the counter stays 5. When in doubt, a trace like the table above settles it.
True or false?
After `count = 0` and `while count < 5:` with `count = count + 1` in the block, count is 5 once the loop ends.
True. The block runs for 0, 1, 2, 3 and 4. After the fifth round count is 5, the test 5 < 5 is False, and the loop ends with count at 5.
Changing the test to `count <= 3` in the loop above still prints three lines.
False. With <= the value 3 also passes the test, so the block runs for 0, 1, 2 and 3: four lines, and count ends at 4.
Leaving a loop early with break
Sometimes the reason to stop is found in the middle of the block, not at the test. The statement break ends the loop at once: the rest of the block is skipped, the condition is not tested again, and Python goes on with the first line after the loop. The program itself keeps running.
A common use is a limited number of tries. The counter sets the most rounds there can be, and break leaves sooner when there is nothing left to repeat:
tries = 0
while tries < 3:
answer = input("Capital of France? ")
tries = tries + 1
if answer.strip().lower() == "paris":
print("Correct!")
break
print("Not that one.")
print(f"Tries used: {tries}")Suppose the user answers Rome and then paris. In the first round the if condition is False, so the program prints Not that one. and goes back to the test with tries at 1. In the second round the answer matches, the program prints Correct!, and break jumps straight to the last line, which prints Tries used: 2. So this loop can end in two ways, and the counter tells which. A correct answer stops it early, through break. Three wrong answers bring tries to 3, and then the test tries < 3 gives False.
The break sits inside an if here, as it almost always does: a break that runs in every round would end the loop in its first round.
You will also see loops written as while True:. The condition True can never become False, so the only way out is a break in the block. This fits a loop whose reason to stop is decided inside the block, such as asking until a reply is acceptable:
while True:
name = input("Your name: ").strip()
if name != "":
break
print("Please type at least one letter.")
print(f"Hello, {name}!")True or false?
When `break` runs, the program stops.
False. break ends only the loop. The program goes on with the first line after the loop: the Hello print in the name example above, the Tries used print in the three-tries example.
The lines of the block that come after a `break` are skipped in the round where it runs.
True. break leaves at once, so nothing below it in the block runs, and the condition is not tested again.
Loops that never end
A while loop stops only in two ways: its condition gives False at a test, or a break runs. If neither can happen, the loop repeats forever. This is called an infinite loop, and it is one of the most common mistakes with while. The usual cause is that nothing inside the block changes what the condition depends on:
count = 0
while count < 3:
print(f"Round {count}")
print("Done")The line count = count + 1 is missing, so count stays 0. The test 0 < 3 is True every time, the screen fills with Round 0, and Done is never printed. The same thing happens in a few other ways:
- A step that goes the wrong way. With
count = count - 1the counter moves away from the limit, so the test staysTrue. - A step with the wrong indentation. If
count = count + 1is indented to the level of thewhileline, it belongs to the lines after the loop, so it never runs inside it. - A condition that cannot become
Falseat all, such aswhile True:with nobreakthat can be reached.
Before running a loop, it helps to ask one question: which line in the block moves the condition towards False?
Stopping a running program
When a program is stuck in a loop, you stop it from the keyboard: click into the terminal where it runs and press Ctrl+C (the Control key and C together, on a Mac too). This sends an interrupt to the program, and Python answers it by raising an error called KeyboardInterrupt. Nothing in the program handles that error, so the program stops and prints an error message. The last line of the message names KeyboardInterrupt. The lines above it show where the program was when you pressed the keys, so they differ from one time to the next. Ctrl+C works the same way when the file was started with uv run: the interrupt reaches the Python program.
A loop that runs forever on purpose is fine when it has a way out. A program that waits for commands until the user types quit uses while True: and a break for exactly that, and Ctrl+C stays available as the emergency stop.
True or false?
Pressing Ctrl+C in the terminal while a Python program is looping stops the program.
True. Ctrl+C makes Python raise KeyboardInterrupt. Nothing handles it, so the program ends, and the last line of its message names KeyboardInterrupt.
A loop with a condition like `count < 3` can never run forever, because its condition is a comparison.
False. Any condition can stay True. If no line in the block changes count, or changes it in the wrong direction, the test is True every time.