While Loop with break

3 min read ·

The break statement is used to immediately stop a loop, even if the loop condition is still True.
When Python encounters break:
  • The loop terminates instantly
  • Control moves to the next statement after the loop

Basic Syntax of break in while Loop

  • break is written inside the loop
  • Usually used with a condition
  • Stops the loop forcefully

Simple Example of while with break

  • Loop starts from 1
  • When i becomes 5, loop stops
  • Numbers after 5 are not printed

while Loop with break and User Input

  • Infinite loop using while True
  • break provides exit condition

break Used to Stop Infinite Loop

  • Loop is infinite by condition
  • break stops it immediately

break with Condition Check

  • Loop exits when condition inside loop becomes True

break inside Nested Conditions


break vs Loop Condition

Without break

With break

  • Loop condition allows up to 10
  • break stops loop earlier

break with String Input


Common Mistake with break

  • Output may be confusing due to update position
Caution

Place break carefully to avoid logical errors.


Real World Example

Real World Scenario

ATM menu exits when user selects Exit option


Exercise

Practice Task
  1. Print numbers from 1 to 10 but stop at 6
  2. Keep asking user input until user types stop
  3. Create a loop that breaks when number is negative
  4. Use while True with break for exit condition