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
breakis written inside the loop- Usually used with a condition
- Stops the loop forcefully
Simple Example of while with break
- Loop starts from 1
- When
ibecomes 5, loop stops - Numbers after 5 are not printed
while Loop with break and User Input
- Infinite loop using
while True breakprovides exit condition
break Used to Stop Infinite Loop
- Loop is infinite by condition
breakstops 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
breakstops 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
- Print numbers from 1 to 10 but stop at 6
- Keep asking user input until user types
stop - Create a loop that breaks when number is negative
- Use
while Truewithbreakfor exit condition