Concepts / Conditional Logic with if Statements

Conditional Logic with if Statements

while True does not decide when to stop. It only creates continued repetition. The if statement supplies the condition, and break supplies the exit action.

  • 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…

The Stop Signal

Interactive programs often need to keep asking for input until the user gives a specific command. A useful Python pattern combines while True with an if statement and break. The loop keeps requesting input, the if statement checks whether the input is the exit command, and break ends the loop when that condition is true.

Following One Complete Cycle

python

The loop begins at while True. Python prompts the user and stores the typed text in line. The if statement then compares line with the exact command done. If the comparison is false, break is skipped, the entered text is printed, and control returns to the beginning of the loop. If the comparison is true, break immediately exits the loop, and execution continues with print("Done!").

while Truebegin iterationUser inputstore in lineline == doneconditionbreakexit loopDone!code after loopprint lineprocess inputtruefalsenext iterationleave loop
What happens next after the program receives each user command, and how does control flow return to the start of the loop or leave it?

Why while True Continues

while True creates the repetition part of the pattern. Because its condition is always true, reaching the bottom of the loop does not finish the loop. Instead, after a non-exit command is processed, execution returns to while True and the program asks for input again. Repetition stops only when execution reaches break.

Inputfirst commandInputnext commandInputdoneChecknot doneChecknot donebreakloop endsrepeatrepeatexit command
How does while True repeatedly execute the input-and-check steps, and where does the loop begin again?
Key point

while True does not decide when to stop. It only creates continued repetition. The if statement supplies the condition, and break supplies the exit action.

What break Does

Definition

break immediately exits the loop. Once Python encounters break, it does not execute the remaining code in that iteration. Execution continues with the code after the loop.

Inside loopchecking inputdonecondition is trueAfter loopprint Done!comparebreak
What condition triggers break, and how does execution move from inside the loop to the code after it?

Tracing User Commands

Suppose the user enters apple, then banana, then done. The first two commands do not match the exit command, so each is printed and the loop starts another iteration. The third command matches exactly. Python executes break, skips the print(line) statement in that iteration, leaves the loop, and then prints Done!.

InputCondition resultActionNext location
applefalsePrint appleBeginning of loop
bananafalsePrint bananaBeginning of loop
donetrueExecute breakCode after loop

Execution trace for the input sequence apple, banana, done.

Output
> apple
apple
> banana
banana
> done
Done!

What do you think happens?

If the user enters done first, will the program print done before printing Done!?

  • Yes, because every input is printed

  • No, because break runs before print(line)

  • Only if the loop has already repeated

Reveal answer
Answer:

No, because break runs before print(line).

When line equals done, the if condition is true. break immediately exits the loop, so the print(line) statement is not executed for that iteration. The code after the loop then prints Done!.

Mistakes That Prevent Exit

  • Common mistake

    Forgetting break

    What it looks like

    The loop checks for the exit command but never executes break.

    Why it fails

    while True continues repeating because nothing tells it to leave.

    Do this instead

    Place break in the branch that handles the intended exit condition.

  • Common mistake

    Using the wrong exit command

    What it looks like

    The program checks for done, but the user enters exit.

    Why it fails

    The condition is based on the command being checked. If the entered text does not match it, the loop treats the input as a non-exit command.

    Do this instead

    Use the documented exit command exactly, or change the condition so it matches the command you intend to accept.

  • Common mistake

    Placing break outside the if statement

    What it looks like

    break is positioned so that it runs regardless of what the user entered.

    Why it fails

    The loop exits without waiting for the specific command.

    Do this instead

    Place break inside the conditional branch that represents the exit condition.

Best practice

Tell the user how to stop the loop, test the exit command, and verify that ordinary input is processed before the next prompt appears.

Practice the Trace

EASY

Trace the input loop for the commands orange, done. For each command, decide whether line is printed, whether the loop repeats, and whether the code after the loop runs.

Hints
  • Compare each command exactly with done.
  • Remember that break skips the remaining code in the current iteration.
  • The code after the loop runs only after break exits the loop.
Worked example

Tracing orange, done

Determine the control flow for the input sequence orange, done.

  1. 1
    Process orange

    orange does not equal done, so break is skipped. The program prints orange and returns to the beginning of the loop.

  2. 2
    Process done

    done equals the exit command, so Python executes break. The current iteration ends immediately, and line is not printed.

  3. 3
    Run code after the loop

    After break exits the loop, the statement after the loop executes and prints Done!.

Result

The program prints orange, then Done!, and does not print done.

Pattern in Practice

This input-loop pattern is useful whenever a program should respond repeatedly to user commands. The same structure can support interactive applications such as chat interfaces, calculators, and menu-driven programs: ask for input, check whether the user signaled to stop, process non-exit input, and repeat.

Key Takeaways

  • while True creates a loop whose condition remains true, so repetition continues until an explicit exit occurs.
  • An if statement checks whether the user's input matches the chosen exit command.
  • break immediately leaves the loop and skips any remaining code in the current iteration.
  • Non-exit input is processed, then control returns to the beginning of the loop.
  • Reliable interactive loops include break, use the intended exit command, place break inside the correct conditional branch, and tell the user how to stop.

Related concepts

More concepts starting with C