Sign in

Intro to Computer Science / Unit 6: Loops

6.2 While Loops

3 practice questionsNot yet reviewed

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 count becomes 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.
  • break exits a loop early. continue skips to the next repetition.

Practice

What does the code above print if the starting line is count = 5?
Which is the most likely cause of an infinite while loop?
Which situation is best suited to a while loop?

Ready for more? Take the Unit 6 test.