The while loop
- Python course
- Beginner
- Lesson 44/116
- 4 min
Learn conditional loops with while.
The while loop
A while loop repeats a block as long as a condition is true:
count = 0
while count < 3:
print(count)
count += 1This prints 0, 1, 2. The condition is checked at the start of each iteration; when it becomes False the loop ends.
In a while loop the condition must become False somewhere, or you get an infinite loop. count += 1 increments count each time.
while vs for
for runs for the length of a collection, while runs as long as a condition is true. Which to pick?
- for: when the collection or range is known.
- while: when the number of iterations is unknown, depending on a condition.
Example: waiting for the user to type 'quit' uses while.
Practice Count with while
Assign count = 0. Write while count < 3: print(count) and count += 1.
Starter code
# while loopSample solution
count = 0
while count < 3:
print(count)
count += 1Expected output
0 1 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What prevents an infinite while loop?
- A print call
- Missing break
- The condition becoming False Correct answer
- A for loop
Explanation: The condition must become False, or the loop is infinite.
2 Complete the while condition
count = 0
while count ____ 3:
print(count)
count += 1
count = 0
while count < 3:
print(count)
count += 1
Explanation: count < 3 produces 0, 1, 2.
3 Match the loop types
| Term | Meaning |
|---|---|
for |
Collection loop |
while |
Condition loop |
range |
Number range |
count += 1 |
Increment |