Python Module 3 – Control flow: decisions, loops and pattern matching
while loops, break, continue and loop else
Repeat code with Python's while loop, stop it at the right moment, use break and continue on purpose, and learn when the else clause of a loop runs.
What you will learn
- Trace a while loop pass by pass and predict when its test turns false
- Write while loops whose stopping condition is sure to become false
- Use break and continue deliberately, updating counters before any continue
- Explain when a loop's else clause runs, including a loop that never ran
Before you start
What you’ll learn · Before you start
What you will learn
- Trace a while loop pass by pass and predict when its test turns false
- Write while loops whose stopping condition is sure to become false
- Use break and continue deliberately, updating counters before any continue
- Explain when a loop's else clause runs, including a loop that never ran
Before you start
On this page
A program that asks for an age until the answer makes sense cannot know whether that takes one try or five, and in
this lesson’s run it takes five. A while loop runs a block again and again for as long as its condition is true. It
is the loop to use when you cannot say in advance how many times the work must happen: until the user types a
sensible answer, until a number reaches 1, until a search finds what it is looking for. (To go through the items of a
list or a range of numbers, the for loop of the next lesson is simpler.)
Below you can step through real runs pass by pass: the test before each pass, the variable that moves the loop towards
its end, and the break, continue and else that change its course. You will also meet the two mistakes that make
a loop run for ever or one pass too far.
A while loop tests its condition before every pass
A while statement looks like an if: the word while, a condition, a colon and an indented block. The difference
is what happens at the end of the block. Python goes back to the top and tests the condition again, and it keeps doing
so until the test comes out false. The test happens before every pass, so when the condition is false from the
start, the body never runs at all.
How a while loop runs, with continue, break and else
Text description of the diagram
The diagram is a flowchart of a while loop, read from the top.
- Python tests the condition. When it is true, the body runs.
- When the body ends, or a continue statement runs inside it, Python goes back to step 1 and tests the condition again.
- When the test comes out false, the loop's else block runs, if the loop has one, and then the code after the loop.
- A break statement in the body leaves the loop at once: Python goes straight to the code after the loop, and the else block does not run.
This program follows the Collatz rule: halve an even number, triple an odd one and add 1, and stop at 1. Step through
it from 6 and watch n, the value the test reads:
Program · collatz_steps.py
n = 6
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
print("Steps:", steps) Variables
- changed in this step
Printed so far
Nothing printed yetSteps: 8
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 37 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
n = 6setsnto6. - Line 2.
steps = 0setsstepsto0. - Line 3.
while n != 1:tests its condition: it is true (nis6), so the body runs. The test comes first. Only becausen != 1is true does the first pass start; withn = 1the body would never run. - Line 4.
n % 2 == 0is true (nis6), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto3(it was6). Key pointnchanges on every pass, andnis what the condition tests. This change is what moves the loop towards its end. - Line 8.
steps += 1changesstepsfrom0to1. - Line 3.
while n != 1:tests its condition: it is true (nis3), so the body runs again (pass 2). - Line 4.
n % 2 == 0is false (nis3), so the else block runs. - Line 7.
n = 3 * n + 1setsnto10(it was3). - Line 8.
steps += 1changesstepsfrom1to2. - Line 3.
while n != 1:tests its condition: it is true (nis10), so the body runs again (pass 3). - Line 4.
n % 2 == 0is true (nis10), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto5(it was10). - Line 8.
steps += 1changesstepsfrom2to3. - Line 3.
while n != 1:tests its condition: it is true (nis5), so the body runs again (pass 4). - Line 4.
n % 2 == 0is false (nis5), so the else block runs. - Line 7.
n = 3 * n + 1setsnto16(it was5). - Line 8.
steps += 1changesstepsfrom3to4. - Line 3.
while n != 1:tests its condition: it is true (nis16), so the body runs again (pass 5). - Line 4.
n % 2 == 0is true (nis16), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto8(it was16). - Line 8.
steps += 1changesstepsfrom4to5. - Line 3.
while n != 1:tests its condition: it is true (nis8), so the body runs again (pass 6). - Line 4.
n % 2 == 0is true (nis8), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto4(it was8). - Line 8.
steps += 1changesstepsfrom5to6. - Line 3.
while n != 1:tests its condition: it is true (nis4), so the body runs again (pass 7). - Line 4.
n % 2 == 0is true (nis4), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto2(it was4). - Line 8.
steps += 1changesstepsfrom6to7. - Line 3.
while n != 1:tests its condition: it is true (nis2), so the body runs again (pass 8). - Line 4.
n % 2 == 0is true (nis2), so the block underif n % 2 == 0:runs. - Line 5.
n = n // 2setsnto1(it was2). - Line 8.
steps += 1changesstepsfrom7to8. - Line 3.
while n != 1:tests its condition: it is false (nis1), so the loop ends.nis 1, so the test is false and the loop is over after 8 passes.stepscounted each of them; the starting 6 is not a step. - Line 9.
print("Steps:", steps)printsSteps: 8. That was the last line, so the program ends.
Each pass changes n, which is what the condition looks at, and counts one step. That is the rule for every while
loop: something in the body must move the loop towards its stopping condition. The next program prints the whole
path from 6 and runs the same loop again from 27:
# The Collatz rule: halve an even number; triple an odd number and
# add 1. Repeat until you reach 1.
n = 6
steps = 0
print(n, end="")
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
print(" ->", n, end="")
print()
print("Steps:", steps)
n = 27
steps = 0
highest = n
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
if n > highest:
highest = n
print("27 needs", steps, "steps and climbs as high as", highest) Output
6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 Steps: 8 27 needs 111 steps and climbs as high as 9232
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 collatz.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Starting from 27, the same loop needs 111 steps and climbs to 9,232 before it falls back to 1. Whether every starting number reaches 1 has never been proved: the claim is called the Collatz conjecture, and research papers have so far proved only weaker statements about it. So a loop’s stopping condition is a promise you should be able to explain, not just hope for.
Key idea
Python tests a while condition before every pass, the first one included. If the body never changes what the
test reads, the test can never turn false, and only a break, a return or an error can end the loop.
Checkpoint
Check: The test before every pass
Why a loop runs for ever, or one pass too far
A loop whose condition never becomes false runs for ever, an infinite loop: A loop whose test never becomes false, so it runs until the program is stopped, with Ctrl-C in a terminal. A body that never changes what the test reads, or a test that its variable steps over, is the usual cause.. The usual
causes are a body that never changes the variable the condition tests, a change in the wrong direction (n += 1
where n -= 1 was meant), and a condition that steps over its target: with n = 1 and while n != 10:, adding 2 on
each pass gives 9 and then 11, so n is never equal to 10. A comparison such as n < 10 stops whether n lands on
10 or jumps past it.
Step through that loop with a cap of 6 passes added to its test, so that this run can end, and watch n jump over 10:
Program · step_over.py
# Meant to stop when n reaches 10. A cap
# of 6 passes keeps this run from going
# on for ever.
n = 1
passes = 0
while n != 10 and passes < 6:
n += 2
passes += 1
print("n is", n, "after", passes, "passes") Variables
- changed in this step
Printed so far
Nothing printed yetn is 13 after 6 passes
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 23 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 4.
- Line 4.
n = 1setsnto1. - Line 5.
passes = 0setspassesto0. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis1andpassesis0), so the body runs. - Line 7.
n += 2changesnfrom1to3. - Line 8.
passes += 1changespassesfrom0to1. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis3andpassesis1), so the body runs again (pass 2). - Line 7.
n += 2changesnfrom3to5. - Line 8.
passes += 1changespassesfrom1to2. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis5andpassesis2), so the body runs again (pass 3). - Line 7.
n += 2changesnfrom5to7. - Line 8.
passes += 1changespassesfrom2to3. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis7andpassesis3), so the body runs again (pass 4). - Line 7.
n += 2changesnfrom7to9. - Line 8.
passes += 1changespassesfrom3to4. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis9andpassesis4), so the body runs again (pass 5). - Line 7.
n += 2changesnfrom9to11. - Line 8.
passes += 1changespassesfrom4to5. - Line 6.
while n != 10 and passes < 6:tests its condition: it is true (nis11andpassesis5), so the body runs again (pass 6). The bugnwent from 9 to 11. It was never equal to 10, son != 10is still true, and only the cap onpassescan end the loop now. - Line 7.
n += 2changesnfrom11to13. - Line 8.
passes += 1changespassesfrom5to6. - Line 6.
while n != 10 and passes < 6:tests its condition: it is false (nis13andpassesis6), so the loop ends. - Line 9.
print("n is", n, "after", passes, "passes")printsn is 13 after 6 passes. That was the last line, so the program ends. The fix Writewhile n < 10:instead. A comparison stops whethernlands on 10 or jumps past it: here after 5 passes, withnat 11.
If it happens in a terminal, press Ctrl-C: Python raises KeyboardInterrupt, which ends the program with a traceback
that shows the line it was running. In the Run bar of this page, Stop ends a run at once, and a run that goes on for
too long is stopped for you.
A common mistake: one step too far
Loops that walk through a list by position are easy to get wrong at the end. Step through this one and watch i:
Program · off_by_one.py
marks = [72, 85, 64]
total = 0
i = 0
while i <= len(marks):
total += marks[i]
i += 1
print("Total:", total) Variables
- changed in this step
Printed so far
Error IndexError: list index out of range Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 15 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
marks = [72, 85, 64]makesmarksa list of 3 items. - Line 2.
total = 0setstotalto0. - Line 3.
i = 0setsito0. - Line 4.
while i <= len(marks):tests its condition: it is true (iis0andmarksis[72, 85, 64]), so the body runs. - Line 5.
total += marks[i]changestotalfrom0to72. - Line 6.
i += 1changesifrom0to1. - Line 4.
while i <= len(marks):tests its condition: it is true (iis1andmarksis[72, 85, 64]), so the body runs again (pass 2). - Line 5.
total += marks[i]changestotalfrom72to157. - Line 6.
i += 1changesifrom1to2. - Line 4.
while i <= len(marks):tests its condition: it is true (iis2andmarksis[72, 85, 64]), so the body runs again (pass 3). - Line 5.
total += marks[i]changestotalfrom157to221. - Line 6.
i += 1changesifrom2to3. - Line 4.
while i <= len(marks):tests its condition: it is true (iis3andmarksis[72, 85, 64]), so the body runs again (pass 4). The bugi <= len(marks)is still true withiat 3, but a list of 3 items has no position 3. The fourth pass starts anyway. - Line 5.
total += marks[i]stops the program withIndexError: list index out of range. The fix The loop asked formarks[3], one step past the end. Withi < len(marks)the test is false at 3 and the loop stops in time.
The list has three items, at positions 0, 1 and 2, but i <= len(marks) lets the loop run a fourth time with i
equal to 3. Use i < len(marks). This is an off-by-one error: A loop that runs one time too many or too few, such as range(1, 10) when 1 to 10 was meant. It usually raises no error and gives a wrong result. More in “for loops with range, enumerate and zip”, and the for loop of the
next lesson does this counting for you, which is why lists are usually walked with for.
Checkpoint
Check: A test that turns false
break leaves a loop, and continue starts the next pass
Two statements change the course of a loop from inside its body:
breakleaves the loop at once. Python goes on with the first line after the loop.continueskips the rest of this pass. In awhileloop, Python goes straight back to testing the condition.
Both act on the innermost loop they are in, and both are normally written inside an if, so that they happen only in
some passes.
while True with break
When the loop can only decide whether to stop halfway through its body, write while True: and leave with break.
Asking for input until it makes sense is the classic case:
# Keep asking until the answer is a whole number from 1 to 120.
while True:
text = input("Your age: ").strip()
if not text.isdecimal():
print("Please type your age in digits.")
continue
age = int(text)
if not 1 <= age <= 120:
print("An age from 1 to 120, please.")
continue
break
print("Thank you. Your age is", age) Input (standard input)
twenty ² 0 250 34
Output
Your age: Please type your age in digits. Your age: Please type your age in digits. Your age: An age from 1 to 120, please. Your age: An age from 1 to 120, please. Your age: Thank you. Your age is 34
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ask_age.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The program was given five answers, shown above its output. “twenty”, “²”, “0” and “250” are rejected, each with a
message, and continue goes back to input() for the next answer; 34 passes both checks and break ends the loop.
The answers do not appear after the prompts because the program read them from
standard streams: The three text channels every program starts with: standard input to read from, standard output for its results and standard error for messages. In Python they are sys.stdin, sys.stdout and sys.stderr. More in “Input and output: print(), input() and stdin”, not from a keyboard; answers typed at a keyboard would have shown
on the screen as they were typed.
isdecimal() is the right check before int(): it is true only for digits that int() can read, including those of
other scripts such as ३४. The similar isdigit() also accepts characters such as ², and int("²") fails with
ValueError.
continue in a counting loop
continue skips everything below it in the body, including a counter you update at the bottom. Move the counter up.
Step through the loop and watch where Python goes after each continue:
Program · skip_failed.py
# -1 marks a reading that the sensor failed to take
readings = [21, 22, -1, 23, -1, 24]
total = 0
count = 0
i = 0
while i < len(readings):
value = readings[i]
i += 1
if value == -1:
continue
total += value
count += 1
print("Good readings:", count)
print("Average:", total / count) Variables
- changed in this step
Printed so far
Nothing printed yetGood readings: 4 Average: 22.5
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 42 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 2.
- Line 2.
readings = [21, 22, -1, 23, -1, 24]makesreadingsa list of 6 items. - Line 4.
total = 0setstotalto0. - Line 5.
count = 0setscountto0. - Line 6.
i = 0setsito0. - Line 7.
while i < len(readings):tests its condition: it is true (iis0andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs. - Line 8.
value = readings[i]setsvalueto21. - Line 9.
i += 1changesifrom0to1. Key pointimoves on at the top of the body, before anything can skip it. Every pass then reads a new position, whatever happens below. - Line 10.
value == -1is false (valueis21), so Python skips the block underif value == -1:. - Line 12.
total += valuechangestotalfrom0to21. - Line 13.
count += 1changescountfrom0to1. - Line 7.
while i < len(readings):tests its condition: it is true (iis1andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs again (pass 2). - Line 8.
value = readings[i]setsvalueto22(it was21). - Line 9.
i += 1changesifrom1to2. - Line 10.
value == -1is false (valueis22), so Python skips the block underif value == -1:. - Line 12.
total += valuechangestotalfrom21to43. - Line 13.
count += 1changescountfrom1to2. - Line 7.
while i < len(readings):tests its condition: it is true (iis2andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs again (pass 3). - Line 8.
value = readings[i]setsvalueto-1(it was22). - Line 9.
i += 1changesifrom2to3. - Line 10.
value == -1is true (valueis-1), so the block underif value == -1:runs. - Line 11.
continueskips the rest of this pass and goes back to the first line of the loop.continueskips the two lines that add the reading, and goes straight back to the test.iis already 3, so the next pass reads 23. - Line 7.
while i < len(readings):tests its condition: it is true (iis3andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs again (pass 4). - Line 8.
value = readings[i]setsvalueto23(it was-1). - Line 9.
i += 1changesifrom3to4. - Line 10.
value == -1is false (valueis23), so Python skips the block underif value == -1:. - Line 12.
total += valuechangestotalfrom43to66. - Line 13.
count += 1changescountfrom2to3. - Line 7.
while i < len(readings):tests its condition: it is true (iis4andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs again (pass 5). - Line 8.
value = readings[i]setsvalueto-1(it was23). - Line 9.
i += 1changesifrom4to5. - Line 10.
value == -1is true (valueis-1), so the block underif value == -1:runs. - Line 11.
continueskips the rest of this pass and goes back to the first line of the loop. - Line 7.
while i < len(readings):tests its condition: it is true (iis5andreadingsis[21, 22, -1, 23, -1, 24]), so the body runs again (pass 6). - Line 8.
value = readings[i]setsvalueto24(it was-1). - Line 9.
i += 1changesifrom5to6. - Line 10.
value == -1is false (valueis24), so Python skips the block underif value == -1:. - Line 12.
total += valuechangestotalfrom66to90. - Line 13.
count += 1changescountfrom3to4. - Line 7.
while i < len(readings):tests its condition: it is false (iis6andreadingsis[21, 22, -1, 23, -1, 24]), so the loop ends. - Line 15.
print("Good readings:", count)printsGood readings: 4. - Line 16.
print("Average:", total / count)printsAverage: 22.5. That was the last line, so the program ends. Four good readings and an average of 22.5. Hadi += 1stayed at the bottom, the first -1 would have sent the loop back to read the same -1 for ever.
Here i += 1 comes before the continue. Had it stayed at the bottom of the body, the first -1 would have sent
the loop back to the test with i unchanged, to read the same -1 for ever.
A counter below the continue
if value == -1: continue above i += 1 sends the loop back to the test with i unchanged, so it reads the same
item for ever. Update the counter at the top of the body, before anything can skip it.
Checkpoint
Check: break and continue
A loop’s else runs only when no break ended it
A while loop may end with an else: block. It runs when the loop stops because its condition is false, and it does
not run when the loop is left with break (or with return or an exception). That makes it a natural fit for
searches: the break means “found it”, and the else means “searched everything, found nothing”. Step through two
searches for a divisor, one that finds it and one that does not:
Program · search_else.py
n = 91
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
print(n, "=", divisor, "x", n // divisor)
break
divisor += 1
else:
print(n, "is prime")
n = 97
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
print(n, "=", divisor, "x", n // divisor)
break
divisor += 1
else:
print(n, "is prime") Variables
- changed in this step
Printed so far
Nothing printed yet91 = 7 x 13 97 is prime
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 50 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
n = 91setsnto91. - Line 2.
divisor = 2setsdivisorto2. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris2), so the body runs. - Line 4.
n % divisor == 0is false (nis91anddivisoris2), so Python skips the block underif n % divisor == 0:. - Line 7.
divisor += 1changesdivisorfrom2to3. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris3), so the body runs again (pass 2). - Line 4.
n % divisor == 0is false (nis91anddivisoris3), so Python skips the block underif n % divisor == 0:. - Line 7.
divisor += 1changesdivisorfrom3to4. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris4), so the body runs again (pass 3). - Line 4.
n % divisor == 0is false (nis91anddivisoris4), so Python skips the block underif n % divisor == 0:. - Line 7.
divisor += 1changesdivisorfrom4to5. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris5), so the body runs again (pass 4). - Line 4.
n % divisor == 0is false (nis91anddivisoris5), so Python skips the block underif n % divisor == 0:. - Line 7.
divisor += 1changesdivisorfrom5to6. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris6), so the body runs again (pass 5). - Line 4.
n % divisor == 0is false (nis91anddivisoris6), so Python skips the block underif n % divisor == 0:. - Line 7.
divisor += 1changesdivisorfrom6to7. - Line 3.
while divisor * divisor <= n:tests its condition: it is true (nis91anddivisoris7), so the body runs again (pass 6). - Line 4.
n % divisor == 0is true (nis91anddivisoris7), so the block underif n % divisor == 0:runs. - Line 5.
print(n, "=", divisor, "x", n // divisor)prints91 = 7 x 13. - Line 6.
breakleaves the loop at once, without reading the items it has not reached. 91 divides by 7, sobreakleaves the loop at once. Python goes on after the whole loop, and the else block is skipped. - Line 11.
n = 97setsnto97(it was91). - Line 12.
divisor = 2setsdivisorto2(it was7). - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris2), so the body runs. - Line 14.
n % divisor == 0is false (nis97anddivisoris2), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom2to3. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris3), so the body runs again (pass 2). - Line 14.
n % divisor == 0is false (nis97anddivisoris3), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom3to4. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris4), so the body runs again (pass 3). - Line 14.
n % divisor == 0is false (nis97anddivisoris4), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom4to5. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris5), so the body runs again (pass 4). - Line 14.
n % divisor == 0is false (nis97anddivisoris5), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom5to6. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris6), so the body runs again (pass 5). - Line 14.
n % divisor == 0is false (nis97anddivisoris6), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom6to7. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris7), so the body runs again (pass 6). - Line 14.
n % divisor == 0is false (nis97anddivisoris7), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom7to8. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris8), so the body runs again (pass 7). - Line 14.
n % divisor == 0is false (nis97anddivisoris8), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom8to9. - Line 13.
while divisor * divisor <= n:tests its condition: it is true (nis97anddivisoris9), so the body runs again (pass 8). - Line 14.
n % divisor == 0is false (nis97anddivisoris9), so Python skips the block underif n % divisor == 0:. - Line 17.
divisor += 1changesdivisorfrom9to10. - Line 13.
while divisor * divisor <= n:tests its condition: it is false (nis97anddivisoris10), so the loop ends and its else block runs. Key point 10 × 10 is more than 97, so the test is false. This loop ended without a break, and that is the one way its else block runs. - Line 19.
print(n, "is prime")prints97 is prime. That was the last line, so the program ends.
For 91, the loop finds the divisor 7 and leaves with break, so the else is skipped. For 97, no divisor up to 9
works and the next one, 10, is too big (10 × 10 is more than 97), so the condition becomes false and the else
reports a prime. Stopping at divisor * divisor <= n is enough because divisors come in pairs, d and n // d,
and the smaller of each pair is never above the square root; a later lesson of this module works that out.
The same search inside a function, tried on four numbers, finds an edge case:
First try · factor_search.py
def describe(n):
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
print(n, "=", divisor, "x", n // divisor)
break
divisor += 1
else:
print(n, "is prime")
describe(91)
describe(97)
describe(2)
describe(1) Output
91 = 7 x 13 97 is prime 2 is prime 1 is prime
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 factor_search.py
Fixed · factor_search_fixed.py
def describe(n):
if n < 2:
print(n, "is neither prime nor composite")
return
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
print(n, "=", divisor, "x", n // divisor)
break
divisor += 1
else:
print(n, "is prime")
describe(91)
describe(97)
describe(2)
describe(1) Output
91 = 7 x 13 97 is prime 2 is prime 1 is neither prime nor composite
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 factor_search_fixed.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The first try gets 1 wrong. For both 2 and 1, divisor * divisor <= n is false from the start, so the body never runs
and the else runs at once. That is right for 2 and wrong for 1, which is not a prime. Remember this edge case: an
else runs even when the loop did no passes at all. The fixed version deals with numbers below 2 before the loop, with
a guard clause: A test at the top of a function that returns at once when an input is wrong or a case is special, so the main work below it needs no else and no extra indentation. More in “Decisions with if, elif and else”.
Version note
New in Python 3.14: a break or continue that would leave a finally block (part of the try statement, covered
with exceptions later in this track) makes Python print SyntaxWarning: 'break' in a 'finally' block or the same for
continue (PEP 765). Such code can silently swallow an error, so move the break out of the finally block.
Checkpoint
Check: The else clause of a loop
Practise: reverse the digits of a number
The exercise takes a number apart with a while loop and arithmetic alone: the last digit is n % 10, the rest is
n // 10, and the loop stops when nothing is left. Its sample tests check the zeros at the end, the minus sign and
the rule against turning the number into text, and a first hint shows the arithmetic.
Exercise · Easy · Python
Reverse the digits of a number with arithmetic
Write two functions that work on the digits of a whole number with arithmetic alone, inside a while loop. Do not turn the number into text: no str(), no f-strings and no slicing (a sample test checks your file for them).
reverse_digits(n)returnsnwith its digits in reverse order:reverse_digits(1234)is4321. Zeros at the end ofndisappear, soreverse_digits(1200)is21; the sign stays, soreverse_digits(-56)is-65; andreverse_digits(0)is0.is_palindrome_number(n)returnsTruewhennreads the same in both directions, such as121,7and0, andFalseotherwise, such as for10and123. Negative numbers are never palindromes, because of the minus sign.
For a positive n, n % 10 is its last digit and n // 10 is n without its last digit.
Starter code · digits.py
def reverse_digits(n):
"""Return n with its digits in reverse order; the sign stays."""
result = 0
return result
def is_palindrome_number(n):
"""Return True when n reads the same both ways (never if n < 0)."""
return False The sample tests · test_digits.py
import ast
from pathlib import Path
from digits import is_palindrome_number, reverse_digits
def test_reverse():
"""reverses the digits of positive numbers"""
assert reverse_digits(1234) == 4321
assert reverse_digits(7) == 7
assert reverse_digits(90817) == 71809
def test_reverse_zeros():
"""drops the zeros at the end, and 0 stays 0"""
assert reverse_digits(1200) == 21
assert reverse_digits(10) == 1
assert reverse_digits(0) == 0
def test_reverse_negative():
"""keeps the minus sign"""
assert reverse_digits(-56) == -65
assert reverse_digits(-1000) == -1
def test_palindromes():
"""recognises numbers that read the same in both directions"""
assert is_palindrome_number(121) is True
assert is_palindrome_number(4884) is True
assert is_palindrome_number(7) is True
assert is_palindrome_number(0) is True
def test_not_palindromes():
"""rejects other numbers, negative ones included"""
assert is_palindrome_number(10) is False
assert is_palindrome_number(123) is False
assert is_palindrome_number(-121) is False
BANNED = ("str", "repr", "format")
def test_arithmetic_only():
"""uses a while loop and no str(), f-strings or slicing"""
path = Path(__file__).with_name("digits.py")
nodes = list(ast.walk(ast.parse(path.read_text(encoding="utf-8"))))
assert any(isinstance(n, ast.While) for n in nodes), "use a while loop"
for node in nodes:
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in BANNED, f"no {node.func.id}()"
assert not isinstance(node, ast.JoinedStr), "no f-strings"
assert not isinstance(node, ast.Slice), "no slicing" A hint
Start with result = 0. While n is more than 0, take its last digit with n % 10, add it to the end of the result with result * 10 + digit, and remove it from n with n // 10. For a negative number, reverse -n (which is positive) and put the minus sign back at the end.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Then answer the questions on loops. The session starts where your answers are weakest and explains, for every choice, why it is right or what it misses:
Practice that adapts to you
Practise this lesson
12 questions about 4 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · When would you use a while loop rather than a for loop in Python?
Use a for loop when you go through something that already exists: the items of a list, the characters of a string,
the numbers of a range. Python keeps the place for you, and the loop cannot run past the end or for ever. Use while
when the number of passes depends on what happens inside the loop: asking until the input is valid, following a rule
until a number reaches 1, retrying until a call succeeds. A while loop makes you write the state, the test and the
update yourself, and those three are where endless loops and loops that run one pass too far come from. So prefer
for whenever it fits, write while True: with a break when the decision comes in the middle of the body, and give
every while loop a test that is sure to become false.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A script waits for a payment by asking the provider for its status every 5 seconds, in a loop written while status != "PAID":. One night a payment was declined, and the script was still running nine hours later. Explain why, and rewrite the loop so that it always stops and reports how it ended.
-
Fresher to mid
A log cleaner walks a list of lines with i = 0 and while i < len(lines):, and skips blank lines with continue. On a file with one blank line it never finishes, and a processor core stays at 100 %. Diagnose the hang, fix it, and make the loop safe for the next person who edits it.
Key takeaways
- A
whileloop tests its condition before every pass; if it is false at the start, the body never runs. - Something in the body must move the loop towards its stopping condition; prefer
<over!=for counters, and press Ctrl-C to stop a runaway loop in a terminal. breakleaves the innermost loop;continuegoes back to the test. Update counters before anycontinue.while True:with abreakin the middle suits input that must be checked before the loop can decide.- A loop’s
elseblock runs only when the loop ends withoutbreak, also when the body never ran: ideal for searches.
Terms in this lesson
- infinite loop
- A loop whose test never becomes false, so it runs until the program is stopped, with Ctrl-C in a terminal. A body that never changes what the test reads, or a test that its variable steps over, is the usual cause.
References
- The Python Language Reference: The while statement (Python Software Foundation)
- The Python Tutorial: break and continue Statements (Python Software Foundation)
- The Python Tutorial: else Clauses on Loops (Python Software Foundation)
- Built-in Exceptions: KeyboardInterrupt (Python Software Foundation)
- Built-in Types: str.isdecimal (Python Software Foundation)
- Built-in Types: str.isdigit (Python Software Foundation)
- Built-in Functions: int() (Python Software Foundation)
- PEP 765: Disallow return/break/continue that exit a finally block (Python Software Foundation)
- What's New In Python 3.14: PEP 765, control flow in finally blocks (Python Software Foundation)
- Almost all orbits of the Collatz map attain almost bounded values (arXiv (Terence Tao))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress