Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 20 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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.

Flowchart of a while loop: test, body, back to the test; break goes straight to the code after the loop, skipping else.Is thecondition true?Run the bodyRun the else block(if there is one)The code afterthe looptrueend of the body,or continuefalsebreak

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.

  1. Python tests the condition. When it is true, the body runs.
  2. When the body ends, or a continue statement runs inside it, Python goes back to step 1 and tests the condition again.
  3. When the test comes out false, the loop's else block runs, if the loop has one, and then the code after the loop.
  4. 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:

Interactive · line by line The Collatz rule from 6, pass by pass Step through the loop and watch n. The lit line has just run, and the chip marks the line that runs next; the test comes back before every pass.

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

After line 9: n is 1; steps is 8.n1steps8
  • changed in this step

Printed so far

Steps: 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.

Line run 9
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. n = 6 sets n to 6.
  3. Line 2. steps = 0 sets steps to 0.
  4. Line 3. while n != 1: tests its condition: it is true (n is 6), so the body runs. The test comes first. Only because n != 1 is true does the first pass start; with n = 1 the body would never run.
  5. Line 4. n % 2 == 0 is true (n is 6), so the block under if n % 2 == 0: runs.
  6. Line 5. n = n // 2 sets n to 3 (it was 6). Key point n changes on every pass, and n is what the condition tests. This change is what moves the loop towards its end.
  7. Line 8. steps += 1 changes steps from 0 to 1.
  8. Line 3. while n != 1: tests its condition: it is true (n is 3), so the body runs again (pass 2).
  9. Line 4. n % 2 == 0 is false (n is 3), so the else block runs.
  10. Line 7. n = 3 * n + 1 sets n to 10 (it was 3).
  11. Line 8. steps += 1 changes steps from 1 to 2.
  12. Line 3. while n != 1: tests its condition: it is true (n is 10), so the body runs again (pass 3).
  13. Line 4. n % 2 == 0 is true (n is 10), so the block under if n % 2 == 0: runs.
  14. Line 5. n = n // 2 sets n to 5 (it was 10).
  15. Line 8. steps += 1 changes steps from 2 to 3.
  16. Line 3. while n != 1: tests its condition: it is true (n is 5), so the body runs again (pass 4).
  17. Line 4. n % 2 == 0 is false (n is 5), so the else block runs.
  18. Line 7. n = 3 * n + 1 sets n to 16 (it was 5).
  19. Line 8. steps += 1 changes steps from 3 to 4.
  20. Line 3. while n != 1: tests its condition: it is true (n is 16), so the body runs again (pass 5).
  21. Line 4. n % 2 == 0 is true (n is 16), so the block under if n % 2 == 0: runs.
  22. Line 5. n = n // 2 sets n to 8 (it was 16).
  23. Line 8. steps += 1 changes steps from 4 to 5.
  24. Line 3. while n != 1: tests its condition: it is true (n is 8), so the body runs again (pass 6).
  25. Line 4. n % 2 == 0 is true (n is 8), so the block under if n % 2 == 0: runs.
  26. Line 5. n = n // 2 sets n to 4 (it was 8).
  27. Line 8. steps += 1 changes steps from 5 to 6.
  28. Line 3. while n != 1: tests its condition: it is true (n is 4), so the body runs again (pass 7).
  29. Line 4. n % 2 == 0 is true (n is 4), so the block under if n % 2 == 0: runs.
  30. Line 5. n = n // 2 sets n to 2 (it was 4).
  31. Line 8. steps += 1 changes steps from 6 to 7.
  32. Line 3. while n != 1: tests its condition: it is true (n is 2), so the body runs again (pass 8).
  33. Line 4. n % 2 == 0 is true (n is 2), so the block under if n % 2 == 0: runs.
  34. Line 5. n = n // 2 sets n to 1 (it was 2).
  35. Line 8. steps += 1 changes steps from 7 to 8.
  36. Line 3. while n != 1: tests its condition: it is false (n is 1), so the loop ends. n is 1, so the test is false and the loop is over after 8 passes. steps counted each of them; the starting 6 is not a step.
  37. Line 9. print("Steps:", steps) prints Steps: 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:

Counting the steps to 1 Python · collatz.py
# 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

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

  1. Question 1 of 2 n = 1, then while n != 1: with a body that prints n. How many times does the body run?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Never

    Python tests a while condition before every pass, the first one included. When it is false from the start, the body never runs, and the program goes on after the loop.

  2. Question 2 of 2 The Collatz loop of the lesson starts with n = 5. How many passes does it make before n is 1?

    Type a number.

    A hint

    Write the values down. 5 is odd, so the first pass makes it 3 × 5 + 1.

    Show the answer: Question 2 of 2

    Answer: 5 passes

    5 becomes 16, then 8, 4, 2 and 1: five changes, so five passes. The test before the sixth pass finds n equal to 1 and ends the loop.

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:

Interactive · line by line A test that n steps over Watch n and the test before each pass. The loop was meant to stop at 10; a cap of 6 passes ends this run.

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

After line 9: n is 13; passes is 6.n13passes6
  • changed in this step

Printed so far

n 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.

Line run 9
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 4.
  2. Line 4. n = 1 sets n to 1.
  3. Line 5. passes = 0 sets passes to 0.
  4. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 1 and passes is 0), so the body runs.
  5. Line 7. n += 2 changes n from 1 to 3.
  6. Line 8. passes += 1 changes passes from 0 to 1.
  7. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 3 and passes is 1), so the body runs again (pass 2).
  8. Line 7. n += 2 changes n from 3 to 5.
  9. Line 8. passes += 1 changes passes from 1 to 2.
  10. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 5 and passes is 2), so the body runs again (pass 3).
  11. Line 7. n += 2 changes n from 5 to 7.
  12. Line 8. passes += 1 changes passes from 2 to 3.
  13. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 7 and passes is 3), so the body runs again (pass 4).
  14. Line 7. n += 2 changes n from 7 to 9.
  15. Line 8. passes += 1 changes passes from 3 to 4.
  16. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 9 and passes is 4), so the body runs again (pass 5).
  17. Line 7. n += 2 changes n from 9 to 11.
  18. Line 8. passes += 1 changes passes from 4 to 5.
  19. Line 6. while n != 10 and passes < 6: tests its condition: it is true (n is 11 and passes is 5), so the body runs again (pass 6). The bug n went from 9 to 11. It was never equal to 10, so n != 10 is still true, and only the cap on passes can end the loop now.
  20. Line 7. n += 2 changes n from 11 to 13.
  21. Line 8. passes += 1 changes passes from 5 to 6.
  22. Line 6. while n != 10 and passes < 6: tests its condition: it is false (n is 13 and passes is 6), so the loop ends.
  23. Line 9. print("n is", n, "after", passes, "passes") prints n is 13 after 6 passes. That was the last line, so the program ends. The fix Write while n < 10: instead. A comparison stops whether n lands on 10 or jumps past it: here after 5 passes, with n at 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:

Interactive · line by line Reading one item past the end Watch i and the test before each pass. The list has three marks, at positions 0, 1 and 2.

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

After line 5: marks is [72, 85, 64]; total is 221; i is 3.marks720851642total221i3
  • 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.

Line run 5
Next line end
Loop pass 4
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. marks = [72, 85, 64] makes marks a list of 3 items.
  3. Line 2. total = 0 sets total to 0.
  4. Line 3. i = 0 sets i to 0.
  5. Line 4. while i <= len(marks): tests its condition: it is true (i is 0 and marks is [72, 85, 64]), so the body runs.
  6. Line 5. total += marks[i] changes total from 0 to 72.
  7. Line 6. i += 1 changes i from 0 to 1.
  8. Line 4. while i <= len(marks): tests its condition: it is true (i is 1 and marks is [72, 85, 64]), so the body runs again (pass 2).
  9. Line 5. total += marks[i] changes total from 72 to 157.
  10. Line 6. i += 1 changes i from 1 to 2.
  11. Line 4. while i <= len(marks): tests its condition: it is true (i is 2 and marks is [72, 85, 64]), so the body runs again (pass 3).
  12. Line 5. total += marks[i] changes total from 157 to 221.
  13. Line 6. i += 1 changes i from 2 to 3.
  14. Line 4. while i <= len(marks): tests its condition: it is true (i is 3 and marks is [72, 85, 64]), so the body runs again (pass 4). The bug i <= len(marks) is still true with i at 3, but a list of 3 items has no position 3. The fourth pass starts anyway.
  15. Line 5. total += marks[i] stops the program with IndexError: list index out of range. The fix The loop asked for marks[3], one step past the end. With i < 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

  1. Question 1 of 2 n = 1, then while n != 8: with n += 3 as the body. What happens?

    Choose one answer.

    A hint

    Write down the values n takes.

    Show the answer: Question 1 of 2

    Answer: It runs for ever: n goes 1, 4, 7, 10 and is never equal to 8

    A test with != must land exactly on its target. Here n steps from 7 to 10, so the loop never ends. A comparison, while n < 8, stops whether n lands on 8 or jumps past it.

  2. Question 2 of 2 marks has 5 items and i starts at 0. Which test lets the loop read every position, 0 to 4, and no other?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: while i < len(marks)

    A list of n items has positions 0 to n − 1, so the loop must stop when i reaches n: while i < len(marks).

break leaves a loop, and continue starts the next pass

Two statements change the course of a loop from inside its body:

  • break leaves the loop at once. Python goes on with the first line after the loop.
  • continue skips the rest of this pass. In a while loop, 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:

Ask again until the answer is valid Python · ask_age.py
# 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

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:

Interactive · line by line continue in a counting loop Watch i and the line that runs after each continue. A reading of -1 is one the sensor failed to take.

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

After line 16: readings is [21, 22, -1, 23, -1, 24]; total is 90; count is 4; i is 6; value is 24.readings210221-12233-14245total90count4i6value24
  • changed in this step

Printed so far

Good 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.

Line run 16
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 2.
  2. Line 2. readings = [21, 22, -1, 23, -1, 24] makes readings a list of 6 items.
  3. Line 4. total = 0 sets total to 0.
  4. Line 5. count = 0 sets count to 0.
  5. Line 6. i = 0 sets i to 0.
  6. Line 7. while i < len(readings): tests its condition: it is true (i is 0 and readings is [21, 22, -1, 23, -1, 24]), so the body runs.
  7. Line 8. value = readings[i] sets value to 21.
  8. Line 9. i += 1 changes i from 0 to 1. Key point i moves on at the top of the body, before anything can skip it. Every pass then reads a new position, whatever happens below.
  9. Line 10. value == -1 is false (value is 21), so Python skips the block under if value == -1:.
  10. Line 12. total += value changes total from 0 to 21.
  11. Line 13. count += 1 changes count from 0 to 1.
  12. Line 7. while i < len(readings): tests its condition: it is true (i is 1 and readings is [21, 22, -1, 23, -1, 24]), so the body runs again (pass 2).
  13. Line 8. value = readings[i] sets value to 22 (it was 21).
  14. Line 9. i += 1 changes i from 1 to 2.
  15. Line 10. value == -1 is false (value is 22), so Python skips the block under if value == -1:.
  16. Line 12. total += value changes total from 21 to 43.
  17. Line 13. count += 1 changes count from 1 to 2.
  18. Line 7. while i < len(readings): tests its condition: it is true (i is 2 and readings is [21, 22, -1, 23, -1, 24]), so the body runs again (pass 3).
  19. Line 8. value = readings[i] sets value to -1 (it was 22).
  20. Line 9. i += 1 changes i from 2 to 3.
  21. Line 10. value == -1 is true (value is -1), so the block under if value == -1: runs.
  22. Line 11. continue skips the rest of this pass and goes back to the first line of the loop. continue skips the two lines that add the reading, and goes straight back to the test. i is already 3, so the next pass reads 23.
  23. Line 7. while i < len(readings): tests its condition: it is true (i is 3 and readings is [21, 22, -1, 23, -1, 24]), so the body runs again (pass 4).
  24. Line 8. value = readings[i] sets value to 23 (it was -1).
  25. Line 9. i += 1 changes i from 3 to 4.
  26. Line 10. value == -1 is false (value is 23), so Python skips the block under if value == -1:.
  27. Line 12. total += value changes total from 43 to 66.
  28. Line 13. count += 1 changes count from 2 to 3.
  29. Line 7. while i < len(readings): tests its condition: it is true (i is 4 and readings is [21, 22, -1, 23, -1, 24]), so the body runs again (pass 5).
  30. Line 8. value = readings[i] sets value to -1 (it was 23).
  31. Line 9. i += 1 changes i from 4 to 5.
  32. Line 10. value == -1 is true (value is -1), so the block under if value == -1: runs.
  33. Line 11. continue skips the rest of this pass and goes back to the first line of the loop.
  34. Line 7. while i < len(readings): tests its condition: it is true (i is 5 and readings is [21, 22, -1, 23, -1, 24]), so the body runs again (pass 6).
  35. Line 8. value = readings[i] sets value to 24 (it was -1).
  36. Line 9. i += 1 changes i from 5 to 6.
  37. Line 10. value == -1 is false (value is 24), so Python skips the block under if value == -1:.
  38. Line 12. total += value changes total from 66 to 90.
  39. Line 13. count += 1 changes count from 3 to 4.
  40. Line 7. while i < len(readings): tests its condition: it is false (i is 6 and readings is [21, 22, -1, 23, -1, 24]), so the loop ends.
  41. Line 15. print("Good readings:", count) prints Good readings: 4.
  42. Line 16. print("Average:", total / count) prints Average: 22.5. That was the last line, so the program ends. Four good readings and an average of 22.5. Had i += 1 stayed 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

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    n = 0
    while n < 5:
        n += 1
        if n % 2 == 0:
            continue
        print(n)
    Show the answer: Question 1 of 2

    Answer: 1, 3 and 5, one per line

    The counter is updated at the top of the body, so continue can never stop it moving. The even numbers skip the print; 1, 3 and 5 are printed, and the test 5 < 5 then ends the loop.

  2. Question 2 of 2 Where does Python go after a break inside a while loop?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: To the first line after the loop

    break leaves the innermost loop it is written in and goes on with the first line after it, skipping the loop's else block.

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:

Interactive · line by line Two searches, two ways to end a loop Step through the search for a divisor of 91, then of 97. Watch where Python goes when each loop ends.

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

After line 19: n is 97; divisor is 10.n97divisor10
  • changed in this step

Printed so far

91 = 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.

Line run 19
Next line end
Loop pass 8
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. n = 91 sets n to 91.
  3. Line 2. divisor = 2 sets divisor to 2.
  4. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 2), so the body runs.
  5. Line 4. n % divisor == 0 is false (n is 91 and divisor is 2), so Python skips the block under if n % divisor == 0:.
  6. Line 7. divisor += 1 changes divisor from 2 to 3.
  7. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 3), so the body runs again (pass 2).
  8. Line 4. n % divisor == 0 is false (n is 91 and divisor is 3), so Python skips the block under if n % divisor == 0:.
  9. Line 7. divisor += 1 changes divisor from 3 to 4.
  10. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 4), so the body runs again (pass 3).
  11. Line 4. n % divisor == 0 is false (n is 91 and divisor is 4), so Python skips the block under if n % divisor == 0:.
  12. Line 7. divisor += 1 changes divisor from 4 to 5.
  13. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 5), so the body runs again (pass 4).
  14. Line 4. n % divisor == 0 is false (n is 91 and divisor is 5), so Python skips the block under if n % divisor == 0:.
  15. Line 7. divisor += 1 changes divisor from 5 to 6.
  16. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 6), so the body runs again (pass 5).
  17. Line 4. n % divisor == 0 is false (n is 91 and divisor is 6), so Python skips the block under if n % divisor == 0:.
  18. Line 7. divisor += 1 changes divisor from 6 to 7.
  19. Line 3. while divisor * divisor <= n: tests its condition: it is true (n is 91 and divisor is 7), so the body runs again (pass 6).
  20. Line 4. n % divisor == 0 is true (n is 91 and divisor is 7), so the block under if n % divisor == 0: runs.
  21. Line 5. print(n, "=", divisor, "x", n // divisor) prints 91 = 7 x 13.
  22. Line 6. break leaves the loop at once, without reading the items it has not reached. 91 divides by 7, so break leaves the loop at once. Python goes on after the whole loop, and the else block is skipped.
  23. Line 11. n = 97 sets n to 97 (it was 91).
  24. Line 12. divisor = 2 sets divisor to 2 (it was 7).
  25. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 2), so the body runs.
  26. Line 14. n % divisor == 0 is false (n is 97 and divisor is 2), so Python skips the block under if n % divisor == 0:.
  27. Line 17. divisor += 1 changes divisor from 2 to 3.
  28. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 3), so the body runs again (pass 2).
  29. Line 14. n % divisor == 0 is false (n is 97 and divisor is 3), so Python skips the block under if n % divisor == 0:.
  30. Line 17. divisor += 1 changes divisor from 3 to 4.
  31. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 4), so the body runs again (pass 3).
  32. Line 14. n % divisor == 0 is false (n is 97 and divisor is 4), so Python skips the block under if n % divisor == 0:.
  33. Line 17. divisor += 1 changes divisor from 4 to 5.
  34. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 5), so the body runs again (pass 4).
  35. Line 14. n % divisor == 0 is false (n is 97 and divisor is 5), so Python skips the block under if n % divisor == 0:.
  36. Line 17. divisor += 1 changes divisor from 5 to 6.
  37. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 6), so the body runs again (pass 5).
  38. Line 14. n % divisor == 0 is false (n is 97 and divisor is 6), so Python skips the block under if n % divisor == 0:.
  39. Line 17. divisor += 1 changes divisor from 6 to 7.
  40. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 7), so the body runs again (pass 6).
  41. Line 14. n % divisor == 0 is false (n is 97 and divisor is 7), so Python skips the block under if n % divisor == 0:.
  42. Line 17. divisor += 1 changes divisor from 7 to 8.
  43. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 8), so the body runs again (pass 7).
  44. Line 14. n % divisor == 0 is false (n is 97 and divisor is 8), so Python skips the block under if n % divisor == 0:.
  45. Line 17. divisor += 1 changes divisor from 8 to 9.
  46. Line 13. while divisor * divisor <= n: tests its condition: it is true (n is 97 and divisor is 9), so the body runs again (pass 8).
  47. Line 14. n % divisor == 0 is false (n is 97 and divisor is 9), so Python skips the block under if n % divisor == 0:.
  48. Line 17. divisor += 1 changes divisor from 9 to 10.
  49. Line 13. while divisor * divisor <= n: tests its condition: it is false (n is 97 and divisor is 10), 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.
  50. Line 19. print(n, "is prime") prints 97 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:

A search with while and else

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

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”.

Prime Number Checker & Generator Check the answers of the factor search for numbers of your own, with the smallest divisor shown.

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

  1. Question 1 of 2 A search loop finds the value it looks for and leaves with break. Does its else block run?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: No; else runs only when the test turns false

    A loop's else block runs when the loop ends because its condition is false, and is skipped when break, return or an exception ends it. In a search, break means found and else means searched everything.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    n = 0
    while n > 0:
        n -= 1
    else:
        print("done")
    Show the answer: Question 2 of 2

    Answer: done

    0 > 0 is false, so the loop makes no passes, and it ended because its test was false, not because of a break. That is exactly when the else block runs, which is the edge case the first factor search got wrong for 1.

Python Online Compiler Try your own while loops with an input box for input(), and Stop for a loop that never ends.

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) returns n with its digits in reverse order: reverse_digits(1234) is 4321. Zeros at the end of n disappear, so reverse_digits(1200) is 21; the sign stays, so reverse_digits(-56) is -65; and reverse_digits(0) is 0.
  • is_palindrome_number(n) returns True when n reads the same in both directions, such as 121, 7 and 0, and False otherwise, such as for 10 and 123. 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.

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.

  1. Question 1 of 12 What does collatz.py print?

    What does this program print? Choose one answer.

    # 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)
    Show the answer: Question 1 of 12

    Answer: it prints

    6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
    Steps: 8
    27 needs 111 steps and climbs as high as 9232

    The loop counts one step for each change of n: 6 becomes 3, 10, 5, 16, 8, 4, 2 and finally 1, eight changes. The starting number is printed before the loop and is not a step. When n reaches 1 the test n != 1 is false, so the loop ends after printing 1.

  2. Question 2 of 12 When does a while loop test its condition?

    Choose one answer.

    Show the answer: Question 2 of 12

    Answer: Before every pass, the first one included

    The test is made before every pass. When it is true the body runs and Python comes back to test again; when it is false the loop ends, possibly before any pass.

  3. Question 3 of 12 With n = 3, which loop prints 3, 2 and 1, one per line, and then stops?

    Choose one answer.

    Show the answer: Question 3 of 12

    Answer: while n > 0: with print(n) and then n -= 1 in the body

    Print first, then move n towards the stop, and stop when n is no longer above 0: three passes, with n at 3, 2 and 1.

  4. Question 4 of 12 Which of these loops never stop? (n starts at 1 in each.)

    Choose every answer that is right.

    Show the answer: Question 4 of 12

    Answer:

    • while n != 10: n += 2
    • while n > 0: n += 1

    Counting up while n > 0 moves away from the stopping condition. Adding 2 to 1 gives only odd numbers, so n != 10 stays true for ever, while n < 10 stops at 11. Tripling reaches 243, which is not below 100, so the loop with n *= 3 ends too.

  5. Question 5 of 12 A loop adds 2 to n on every pass. Why is while n < 10: safer than while n != 10:?

    Choose one answer.

    Show the answer: Question 5 of 12

    Answer: It stops whether n lands on 10 or jumps past it

    A test with != is false for one value only, so the loop must land on it exactly. A comparison such as n < 10 is false from 10 up and ends the loop either way.

  6. Question 6 of 12 A loop starts with i = 0 and reads marks[i] while i <= len(marks) - 1, adding 1 to i each pass. What does it do?

    Choose one answer.

    Show the answer: Question 6 of 12

    Answer: It reads every position once and stops

    For whole numbers, i <= n - 1 and i < n are true for exactly the same values of i. Both read positions 0 to n − 1 and stop.

  7. Question 7 of 12 What does this print?

    Read the code, then choose one answer.

    n = 0
    while n < 4:
        n += 1
        if n == 2:
            continue
        print(n)
    Show the answer: Question 7 of 12

    Answer: 1 3 4

    n goes up before the continue, so the loop always moves on. When n is 2, continue skips the print and goes back to the test. The loop stops after n reaches 4, which is printed because 4 < 4 is only tested afterwards.

  8. Question 8 of 12 A break runs inside a while loop that is itself inside another loop. What does it leave?

    Choose one answer.

    Show the answer: Question 8 of 12

    Answer: Only the innermost loop, the one it is written in

    break leaves the innermost loop it is in; the outer loop goes on with its next pass. Leaving several loops at once takes a flag or a function that returns, as the lesson on nested loops shows.

  9. Question 9 of 12 A program asks for a PIN at most 3 times and must stop as soon as the right PIN is typed. Which structure fits?

    Choose one answer.

    Show the answer: Question 9 of 12

    Answer: tries = 0 and while tries < 3: that asks, adds 1 to tries and breaks on the right PIN

    Two things can end this loop: three tries used up, which the test checks, and the right PIN, which break handles. An else block on the loop can then report that all three tries failed.

  10. Question 10 of 12 When does the else block of a while loop run?

    Choose one answer.

    Show the answer: Question 10 of 12

    Answer: When the condition is false, also if it was false before the first pass, but not after a break

    The else block runs when the loop stops because its condition tested false, which may happen on the very first test: that is why describe(1) in the first try of the factor search printed "1 is prime". A break (or a return or an exception) leaves the loop without running it.

  11. Question 11 of 12 In the first try of the factor search, why does describe(1) print "1 is prime"?

    Choose one answer.

    Show the answer: Question 11 of 12

    Answer: 2 × 2 <= 1 is false at once, so the loop makes no passes and its else runs

    For n = 1 the test divisor * divisor <= n is 4 <= 1, false from the start, so the else block runs straight away. The fixed version handles numbers below 2 with a guard clause before the loop.

  12. Question 12 of 12 A search loop leaves with break when it finds the value. Where does a "not found" message go, so that it prints only when nothing was found?

    Choose one answer.

    Show the answer: Question 12 of 12

    Answer: In an else block of the loop

    break means found, and a loop's else means the loop ran out without a break, so else is where "not found" belongs. A flag variable set before the break does the same job with an if after the loop.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A while loop 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.
  • break leaves the innermost loop; continue goes back to the test. Update counters before any continue.
  • while True: with a break in the middle suits input that must be checked before the loop can decide.
  • A loop’s else block runs only when the loop ends without break, 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.