while Loops
A while loop repeats while a condition is True. Unlike a for loop, it does not automatically move to the next value. You must update something so it can stop.
By the end of this lesson, you can:
- Write a stopping condition
- Update a loop variable
- Count upward and downward
- Recognize an infinite loop
- Repeat input until a match
while Loops lesson progress0%
Course progress: 0% · 0 of 12 steps completed in this module
Learn · Repeat while a condition is true
Repeat while a condition is true
Python checks the condition before every repetition. When it becomes False, the loop ends. The body must be indented and should change a value used by the condition.
Pattern
while condition:
instruction
updateCode
count = 1
while count <= 4:
print(count)
count += 1Output
1 2 3 4
Why it works
- count starts at 1.
- The condition allows values through 4.
- count increases each time; at 5 the loop stops.
Common mistake
Not this
while count <= 4:
print(count)Try this
while count <= 4:
print(count)
count += 1Without an update, count never changes and the loop may run forever.