Intro to Computer Science / Unit 6: Loops
6.2 While Loops
Notes
A while loop repeats as long as its condition is True. Use it when you do not know in advance how many repetitions you need.
count = 1
while count <= 3:
print(count)
count = count + 1
- This prints 1, 2, 3. When
countbecomes 4, the condition is False and the loop stops. - You must change something inside the loop that eventually makes the condition False.
- An infinite loop never stops, for example when you forget
count = count + 1. breakexits a loop early.continueskips to the next repetition.
Practice
What does the code above print if the starting line is
count = 5?5 <= 3 is False at the start, so the body never runs.
Which is the most likely cause of an infinite while loop?
If the condition never becomes False, the loop never ends.
Which situation is best suited to a while loop?
The number of attempts is unknown, so a while loop that checks a condition is best.
Ready for more? Take the Unit 6 test.