CHAPTER 12 · BEGINNER4 min read

While loops and loop control

Repeat while a condition holds, prove that a loop can finish, and use break and continue carefully.

Python 3.12+Free to readModule 3 of 13
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Trace the condition, body, and state update of a while loop.
  • Use break and continue without accidentally preventing progress.
  • Explain when a loop else clause executes.

01Repeat while a condition remains true

A while loop checks its condition before each iteration. When the condition is true, Python runs the indented body and then checks again. When it becomes false, the loop ends. Unlike a for loop, a while loop does not automatically take the next item from a collection. Your program must make the relevant state move toward completion.

For a countdown, the state is the number remaining and the update subtracts one. Trace the first check, one full body execution, and the next check. Notice that a loop may execute zero times when its condition is false at the beginning. Prefer for when visiting a known collection; use while when repetition is naturally governed by changing state rather than a predetermined sequence of items.

countdown.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Find the progress that makes termination possible

Before running a while loop, identify what can make its condition false. A retry counter should increase; a remaining balance should decrease; a stream of work should eventually supply an ending signal. If nothing relevant changes, the loop may continue indefinitely. An iteration limit can make a simulation or retry policy explicitly bounded, but it should represent an intentional rule rather than hide an unexplained bug.

The example models repeated practice until a target is reached. The final total can overshoot the target because the condition is checked before adding the next session. That is expected here: the requirement is to reach at least 50 minutes. If the requirement were to reach exactly 50, the update rule would need a different design. A terminating loop can still implement the wrong business rule.

reach_a_target.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Stop early or skip an iteration deliberately

break exits the nearest enclosing loop immediately. It is useful when a search has found the first suitable item or an ending marker means later values should be ignored. continue skips the rest of the current body and moves to the next iteration. In a while loop, that means returning to the condition check; in a for loop, it means requesting the next item.

A continue placed before a while loop's progress update can accidentally repeat the same state forever. Keep that update reachable on every path that continues. This deterministic example processes a fixed list as if it were a stream of readings: negative readings are ignored and zero is the stop marker. Printing the result after the loop makes the difference between skipping one item and ending the whole process visible.

readings_with_marker.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Use loop else for completion without break

Both for and while loops can have an else clause. It executes when the loop finishes normally without a break: a for loop exhausts its items, or a while condition becomes false. It can execute even when the loop body runs zero times. Read this else as 'no break occurred,' rather than associating it with the nearest condition inside the loop.

A search demonstrates the idea. If an acceptable reading appears, break suppresses the fallback message. If every item is examined without finding one, else reports that outcome. A separate found flag can express the same behavior and may feel clearer initially. Choose the version your readers can explain reliably. If a loop needs several flags, nested exits, and complicated updates, consider simplifying the task into smaller steps.

search_with_fallback.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • A while loop must change relevant state or reach a deliberate exit.
  • break ends the nearest loop; continue skips the remainder of one iteration.
  • Loop else describes completion without break, including the empty case.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Count bounded attempts

Use a while loop to print Attempt 1, Attempt 2, and Attempt 3, then print Finished. Start attempts at zero and make the update explicit.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
attempts = 0while attempts < 3:    attempts += 1    print(f"Attempt {attempts}")print("Finished")

Incrementing before display gives human-readable numbers 1 through 3. The counter eventually makes attempts < 3 false, so the loop terminates.

02

Search for the first long name

From ['Ada', 'Mira', 'Noor', 'Alexandra'], print the first name longer than five characters and stop searching. If none qualifies, print No long name. Use break and a loop else clause.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
names = ["Ada", "Mira", "Noor", "Alexandra"]for name in names:    if len(name) > 5:        print(name)        breakelse:    print("No long name")

Alexandra is the first qualifying value. The break ends the search and prevents the else clause from printing its fallback. An empty list would take the fallback path.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01A while condition is false on the first check. How many times does its body run?
02Why can continue cause an infinite loop in a counter-based while loop?
03When does a loop's else clause run?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Count bounded attempts

Use a while loop to print Attempt 1, Attempt 2, and Attempt 3, then print Finished. Start attempts at zero and make the update explicit.

EXPECTED OUTPUT
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Attempt 0
Finished
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this chapter, when you want a second angle or the full details.

One chapter closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.