Andromeda
Note

while Loops (Python)

Definition

A control flow statement that repeatedly executes a block of code as long as a specified condition remains True.

Why It Matters

for loops are for knowns; while loops are for the unknown. Without while loops, a program would be unable to wait for user input, monitor a sensor, or react to an unpredictable world. They are the “pulse” of any interactive or long-running system.

Core Concepts

  • Execution Flow:
    • At the end of the block, execution jumps back to the start of the while statement to re-evaluate the condition.
    • If True, the block runs again; if False, execution skips the block and continues after it.
  • Infinite Loops: A failure state where the condition never becomes False. Tactical Tip: If your program seems “stuck”, use Ctrl+C to force termination.
  • Flow Interruptions:
    • break: “Break out” of the loop immediately without re-checking the condition.
    • continue: “Jump back” to the start of the loop immediately to re-evaluate the condition.
  • Ending the Program: Use sys.exit() to terminate the entire program immediately, regardless of where it is in the execution flow.
count = 0
while count < 10:
    if count == 5:
        break
    print(count)
    count += 1

Connected Concepts