LEARN PYTHON | While Loops And Loop Control

Lesson objective

Use while conditions, initialise and update loop state, apply break and continue carefully, and recognise valid termination and infinite-loop risks.

Learn

02.4 | WHILE LOOPS AND LOOP CONTROL

01 | REPEAT WHILE A CONDITION HOLDS

A for loop suits a known sequence. A while loop suits repetition controlled by a condition that may change as the program runs.

Python tests the while condition before each body execution. If it is true, the indented body runs, then Python returns to the condition. If it is false, the body is skipped and execution continues after the loop.

The body is the repeated instruction group. One run of that body is an iteration. The condition decides whether the next iteration starts.

count = 1
while count <= 3:
    print(count)
    count += 1
print("Finished")

EXPECTED OUTPUT

1
2
3
Finished

02 | INITIALISE, TEST AND UPDATE

The starting assignment gives the condition a value it can read. The condition controls entry. The update changes the state so a later test can become false.

For count starting at one with condition count <= 3, outputs are one, two and three. Each update adds one. The next condition test sees four, becomes false and ends the loop.

Without the update, count would stay one and the condition would remain true. Do not assume while automatically increases a counter.

03 | ZERO ITERATIONS ARE POSSIBLE

If count starts at four, count <= 3 is already false. The body runs zero times. This is a pre-condition loop: testing comes before doing.

That differs from a repeat-until structure in some pseudocode languages, which tests after a first body execution. Python does not have a built-in repeat-until statement. A carefully designed while loop can provide retry behaviour.

Check the initial condition during tracing, not only what happens after a hypothetical first iteration.

count = 4
while count <= 3:
    print(count)
    count += 1
print("Nothing needed repeating")

EXPECTED OUTPUT

Nothing needed repeating

04 | RETRY AN OUT-OF-RANGE VALUE

Ask for an INTEGER score once, then repeat while it is outside zero to one hundred. The body gives feedback and receives a new value. A valid initial score skips the retry body.

The new input assignment is essential: it gives the next condition test something different to consider. This version assumes the response is suitable integer text. Handling words or empty input comes in the debugging lesson.

score = int(input("Score from 0 to 100: "))
while score < 0 or score > 100:
    print("That score is outside the allowed range")
    score = int(input("Try a score from 0 to 100: "))
print("Accepted score:", score)

05 | A SENTINEL MARKS THE END

A sentinel is a special input used to stop rather than represent ordinary data. For a total of non-negative counts, -1 can mean finish. It must be distinct from an otherwise valid input value.

Read a value, then keep adding while it is not the sentinel. The sentinel is not added. This example assumes all non-sentinel values are valid non-negative integers.

The next input at the bottom supplies the next condition test. Forgetting it would repeatedly add the same number forever.

total = 0
value = int(input("Count, or -1 to finish: "))
while value != -1:
    total += value
    value = int(input("Count, or -1 to finish: "))
print("Total:", total)

06 | BREAK LEAVES THE LOOP

break exits the nearest enclosing loop immediately. Code later in that body is skipped, then execution continues after the loop.

A while True loop has a permanently true condition, so it needs a reachable break or another deliberate exit. In this input-driven example, the user types quit to reach break.

A break does not mean every function and program stops. It leaves one enclosing loop. With nested loops, it leaves only the innermost one.

while True:
    command = input("Type a command, or quit: ").strip()
    if command == "quit":
        break
    print("Command received:", command)
print("Session ended")

07 | CONTINUE SKIPS THE REST OF THIS ITERATION

continue does not leave the loop. It skips the remaining body statements and proceeds towards the next iteration. In while, that means testing the condition again.

Be careful with updates below continue. If the update is always skipped, a while condition can remain true forever. In the example, the update happens before the possible continue, so every iteration makes progress.

pass is different: it does nothing and then the following statement still runs. It is not a skip-to-next-iteration command.

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue
    print(count)

EXPECTED OUTPUT

1
2
4
5

08 | USE A CLEAR TERMINATION REASON

A loop may stop because its condition becomes false, because break executes, or because an unhandled exception interrupts the program. These are different outcomes.

When tracing, record the actual exit route. A program crashing on invalid input has not completed its intended task merely because the loop stopped.

For a bounded activity, a condition such as attempts < max_attempts and not won makes both reasons visible. An update can increase attempts, while a successful result can set won = True.

09 | WATCH A COUNTING WHILE LOOP

The demo traces a fixed counting loop with a positive step. Predict its printed values and the final failed condition test. Limits keep the browser activity small and safe.

    Compare start 1, limit 3 with start 4, limit 3. The second should have no body executions.

    10 | SPOT AND STOP AN INFINITE LOOP

    An infinite loop lacks a reachable intended stop. Missing updates, wrong-direction changes, a sentinel that is never read or continue skipping progress can all cause it.

    If your program repeats unexpectedly, use the editor or terminal’s interrupt action; Ctrl+C commonly interrupts a running terminal program. Then inspect the last condition and the statements that can change it.

    Do not deliberately run an unbounded broken loop just to prove it is broken. Trace its unchanged state first. A bounded teaching trace gives evidence without flooding the terminal.

    11 | CHOOSE FOR OR WHILE FROM THE TASK

    Use for with range when a known sequence or fixed number of attempts fits the requirement. Use while when the continuation depends on changing state, such as an input remaining invalid or a target not yet reached.

    Either structure can sometimes express the same task, but one may make the control clearer. A guessing game with a win flag and attempt limit can use while; a multiplication table naturally uses for.

    Challenge: total non-negative counts until -1. Then write a command loop that ends on quit. For each, identify the sentinel, the update and the final output.

    PUT YOUR SKILLS TO WORK

    Use the Section 2 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.

    Section 2 challenges Python course navigation

    MATCH THE PYTHON TERM TO ITS MEANING

    Terminology

    Terminology

    while

    Repeats its body while a condition is true.

    Pre-condition loop

    Tests before each body execution.

    Loop state

    Values affecting whether repetition continues.

    Initialisation

    Giving loop state a starting value.

    Update

    Changing state during repetition.

    Termination

    Ending the intended repetition.

    Zero iterations

    No body execution because entry condition is false.

    Sentinel

    A special value signalling the end of ordinary input.

    break

    Leaves the nearest enclosing loop.

    continue

    Skips the remaining body for the current iteration.

    pass

    A no-operation statement; following code still runs.

    Infinite loop

    Repetition without a reachable intended termination.

    Retry

    Another attempt after unacceptable input.

    Flag

    A Boolean recording a state such as won.

    Attempt limit

    A bound on accepted attempts.

    Interrupt

    Stopping running code from the environment.

    Nearest enclosing loop

    The innermost loop surrounding the statement.

    Exit route

    The reason execution leaves the loop.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which describe while?
    2. Which help a counting loop terminate?
    3. Which describe a sentinel?
    4. Which describe break?
    5. Which describe continue?
    6. Which describe pass?
    7. Which can cause infinite repetition?
    8. Which loop choices fit?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Trace count 1 while count <= 3, printing then adding one.

    2. Explain zero iterations.

    3. Explain a retry’s new input assignment.

    4. Define a sentinel with an example.

    5. Compare break and continue.

    6. Explain pass versus continue.

    7. Explain an update skipped by continue.

    8. Suggest evidence when a loop runs unexpectedly.

    CODE IT | YOUR INDEPENDENT CHALLENGE

    Total non-negative counts until -1, and create a separate quit-controlled command loop. Identify every exit route.

    Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for While Loops And Loop Control is coming soon. Complete the matching task and written questions in your exercise book.