Beginner level · Module 2: Decisions and Loops · Lesson 3 of 3
while Loops, break and continue
Repeat until a condition changes, such as a menu that runs until the user chooses to exit.
In this lesson you will
- Write while loops that always terminate
- Use break to exit and continue to skip an iteration
Key concepts
loop conditioninfinite loopsentinel valuebreak/continue
The lesson
A while loop repeats as long as its condition stays True. It suits situations where you do not know in advance how many repetitions are needed — such as a menu that runs until the user chooses Exit.
while True: creates a loop that only ends when the code reaches break. continue skips the rest of the current repetition and goes back to the top, which is useful for ignoring invalid choices.
Every while loop needs a way out. If nothing ever makes the condition False or reaches break, the program runs forever; press Ctrl+C in the terminal to stop it.
Step by step
- Print a numbered menu inside while True.
- Read the user's choice with input().
- Handle each option with if/elif; use continue for an invalid choice.
- Use break when the user chooses Exit and print a goodbye message.
Practice activity
Build a menu loop with options 1) add sale 2) show total 3) exit that keeps running until the user chooses 3.
Expected result: The menu program runs repeatedly, keeps a running total, and exits cleanly on option 3.
Check your understanding
-
What is a sentinel value?
Show answer
A special input (for example 'q' or 0) that signals the loop to stop.
-
What is the difference between break and continue?
Show answer
break leaves the loop completely; continue skips to the next iteration.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.