Learning outcomes
By the end of this lecture, you should be able to:- write correct
whileloop syntax - explain execution flow line by line
- avoid infinite-loop mistakes
- solve simple counting tasks with
while
Syntax
- loop runs while condition is
True - stops when condition becomes
False
Execution flow
- evaluate condition
- if
True, run body - update loop variable
- return to step 1
- if
False, exit loop
Counting example
Dry-run table
| Iteration | i before | condition i <= 5 | printed | i after |
|---|---|---|---|---|
| 1 | 1 | True | 1 | 2 |
| 2 | 2 | True | 2 | 3 |
| 3 | 3 | True | 3 | 4 |
| 4 | 4 | True | 4 | 5 |
| 5 | 5 | True | 5 | 6 |
| stop | 6 | False | - | - |
Reverse counting example
Infinite loop trap
inever changes, condition alwaysTrue
while with boolean input loop
Exam hints and traps
- update must move variable toward stop condition
- indentation errors can move update outside loop
while Trueneeds explicitbreakinside
Practice
- Print even numbers from 2 to 20.
- Print numbers from 10 to 1.
- Find error:
Answer key
- Indentation error (
print(i)must be indented in loop block).
