Concepts / Recognizing and Handling Infinite Loops

Recognizing and Handling Infinite Loops

The break statement exits a loop immediately, skipping any remaining code in the loop body.

  • Programming
Interactive lab

Try it: while Loops, break and continue

How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.

How it works

  1. Evaluate the condition. If it is False, skip the body and continue after the loop.
  2. If it is True, run the body from the top, then go back and evaluate the condition again.
  3. continue skips the rest of the body and goes straight back to the condition check.
  4. break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
  5. If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.

Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.

Educational simulation

Loading the simulation…

When Repetition Needs a Decision Inside

Some loops do not know in advance exactly when they should stop. Instead, the program performs an action, examines what happened, and then decides whether to continue. Python's break statement is designed for this situation: when execution reaches break inside a loop, the loop ends immediately and the remaining code in that loop body is skipped.

What do you think happens?

A program repeatedly asks for input. What should happen after the user enters hello, world, and then done?

  • The loop stops after hello

  • The loop prints hello and world, then stops before printing done

  • The loop prints all three inputs and continues forever

Reveal answer
Answer:

The loop prints hello and world, then stops before printing done.

For hello and world, the stop condition is false, so the loop prints the input and repeats. When the input is done, break executes immediately, so the print of that input is skipped and the loop continues with the statement after the loop.

The Immediate Effect of Break

break does two things at the moment it executes. First, it exits the loop. Second, it skips every statement that would otherwise come later in the current loop body. Control then continues with the statement after the loop. This is different from merely skipping one statement: break ends the repetition itself.

Loop bodyStop conditionbreakAfter the loopRemaining statementsskippedNext iterationreach conditionyesexit immediatelynorepeat
When break executes inside the loop body, what code runs next, and which remaining statements are skipped?

Tracing the Done Signal

The source example asks the user for input repeatedly until the word done is entered. Each repetition prints a prompt and waits for input. The program then checks whether the input equals done. If it does not, the program prints the input and returns to the top of the loop. If it does, break executes before the input-printing statement.

Loop startInput prompt>User inputhello, world, or doneInput equals donebreakDone!Print inputstartreceivecheckyesleave loopnorepeat
How does control flow through the loop when the exit check occurs after input is received and before the ordinary output?
Worked example

hello, world, done

Trace the source program when the user enters hello, then world, then done.

  1. 1
    First repetition

    The loop starts, prints the prompt, and receives hello. The input is not done, so break does not execute. The program prints hello and returns to the top.

  2. 2
    Second repetition

    The prompt appears again and the user enters world. The input is still not done, so the program prints world and returns to the top.

  3. 3
    Third repetition

    The prompt appears again and the user enters done. The condition is true, so break executes. The program skips the statement that would print the input and exits the loop.

  4. 4
    After the loop

    The statement after the loop prints Done! once.

Result

The ordinary input output is hello followed by world. The input done is not printed by the loop, and Done! is printed once after the loop.

While True and Internal Exit Checks

The while True pattern creates an intentional infinite loop. Its repetition condition is always true, so the loop needs a break statement inside its body to end. This pattern is useful when the program discovers the stopping information during the loop, such as after receiving input. The exit condition can be placed where that information becomes available rather than being forced to appear at the top.

while TruerepeathellocontinuebreakAfter the loopworldcontinuedonestop conditioniterationrepeatiterationrepeatiterationcondition metterminate
How does a while True loop continue repeating, and how does the later break condition terminate it?

Affirmative Stop Conditions

There are two ways to describe the same stopping behavior. A traditional loop condition can say to keep going while the input is not done. The while True pattern can instead say to stop when the input is done. Both approaches can perform the same task, but the second states the exit event directly.

StyleWhat the condition expressesWhat the reader must reason about
Negative continuationKeep going while the input is not doneReason about a negated condition
Affirmative stopStop when the input is doneRead the stopping event directly

The two descriptions can produce the same loop behavior, but affirmative wording can be clearer when the stop condition is complex or when there are multiple possible exit points.

Best practice

Prefer the while True and break pattern when the exit condition is discovered inside the loop or when saying stop when this happens makes the logic easier to read. When the exit condition is simple and known before the loop starts, a traditional loop condition is often clearer.

Mistakes That Keep Loops Running

  • Common mistake

    Assuming break skips only the current statement.

    What it looks like

    The loop reaches break and then is expected to execute the next print statement inside the same loop body.

    Why it fails

    break exits the loop immediately and skips the remaining code in that loop body.

    Do this instead

    Treat the statement after the loop as the next destination after break executes.

  • Common mistake

    Using while True without a reachable stopping condition.

    What it looks like

    The loop repeats, but no realistic input or event causes break to execute.

    Why it fails

    while True intentionally keeps the loop condition true, so break is needed to terminate the loop.

    Do this instead

    Verify that the stop condition can occur under realistic conditions.

  • Common mistake

    Checking the stop condition only at the top when the required information appears later.

    What it looks like

    The program must receive input before it can determine whether it should stop.

    Why it fails

    The exit decision depends on information discovered inside the loop body.

    Do this instead

    Place the exit check after the input or other event that supplies the stopping information.

  • Common mistake

    Describing a stop condition as a difficult negative continuation condition.

    What it looks like

    Thinking through keep going while the input is not done when the important event is that the input is done.

    Why it fails

    Negation can make the reader reason through an extra logical step.

    Do this instead

    When appropriate, express the condition affirmatively as stop when the input is done.

Practice the Control Flow

EASY

Trace the input sequence hello, done for the source-style input loop. For each input, identify whether break executes, whether the ordinary input-printing statement runs, whether the loop repeats, and what happens after the loop.

Hints
  • For hello, compare the input with the stop word done.
  • For done, remember that break skips the remaining statements in the loop body.
  • The statement after the loop runs only after the loop has exited.
  1. 1
    To solve the trace, hello does not meet the stop condition, so it is printed and the loop repeats. done meets the stop condition, so break exits immediately and the input-printing statement is skipped. The statement after the loop then runs.

Key Takeaways

  1. 1
    break exits a loop immediately and skips the remaining statements in the current loop body.
  2. 2
    while True creates an intentional infinite loop that must reach break to terminate.
  3. 3
    An exit check can appear inside the loop body, wherever the needed information becomes available.
  4. 4
    Affirmative stop wording describes when to stop directly, instead of describing the negated condition for continuing.
  5. 5
    Use a traditional loop condition when the exit condition is simple and known before the loop starts.
  6. 6
    Always verify that a break statement can execute under realistic conditions.

At a glance

  • break ends the loop immediately and skips all remaining code in that loop body.
  • The while True and break pattern is useful when the program discovers its stopping condition during the loop.
  • Exit checks can be placed after input or another event inside the loop, rather than only at the top.
  • Affirmative conditions such as stop when the input is done can be clearer than negative continuation conditions.
  • A loop using while True must have a realistic path to break, or it will remain infinite.

Related concepts

More concepts starting with R