While Loops
in Python
Master condition-based repetition to make your programs loop until a goal is reached: from simple counters to input validation and beyond.
What Is a Loop?
A loop tells the computer to repeat a block of code multiple times instead of writing the same instructions over and over. Loops are one of the most powerful ideas in programming: they let a few lines do the work of thousands.
The while Statement
A while loop checks a condition before each iteration. If the condition is True, the indented body runs. Then Python jumps back to check again. This cycle continues until the condition becomes False.
How a While Loop Flows
Anatomy of a while Loop
while vs for
Python has two main loops. Choose the right one based on whether you know in advance how many times to repeat.
| while loop | for loop | |
|---|---|---|
| Repeat count | Unknown in advance | Known or iterable |
| Controlled by | A boolean condition | A sequence or range |
| Risk of infinite loop | Higher: you manage the update | Lower: auto-advances |
| Best for | Input validation, games, search | Iterating lists, counted reps |
How to Write a While Loop
Example 1: Countdown
Example 2: Input Validation
A very common use of while: keep asking the user for input until they give a valid answer.
Example 3: Sentinel Value Pattern
A sentinel value is a special input that signals "stop". The loop keeps running until it sees the sentinel.
break and continue
The else Clause on Loops
Python uniquely lets you attach an else block to a while loop. The else body runs only if the loop finishes normally (condition became False) and does not run if the loop was terminated by break.
Infinite Loops
An infinite loop occurs when the condition never becomes False. Your program freezes and must be forcibly stopped.
Common Mistakes
While Loop Cheat Sheet
| Concept | Syntax / Keyword | Purpose |
|---|---|---|
| Basic loop | while condition: | Repeat while True |
| Infinite loop | while True: | Loop until break |
| Early exit | break | Leave loop immediately |
| Skip iteration | continue | Jump to next check |
| Completion block | else: | Runs if no break |
| Sentinel pattern | Priming read + loop | Stop on special value |
Question 1 of 5
What is the output of this code?
Question 2 of 5
Which keyword immediately exits a while loop?
Question 3 of 5
How many times does the body of this loop execute?
Question 4 of 5
What happens if you forget to update the control variable inside a while loop?
Question 5 of 5
What is the value of total after this code runs?