Module 3

while loops

Repeating while a condition is true.

Keep going while true

A while loop repeats as long as its condition is true. It is useful when you do not know in advance how many times you need to loop.

Python
count = 0
while count < 3:
    print(count)
    count = count + 1
0 1 2

The loop checks the condition before each iteration. When count reaches 3, the condition is false and the loop stops.

A common mistake

If you never change the condition, the loop runs forever. Always make sure the condition will eventually become false.

How many times does this loop print? count = 0 while count < 3: print(count) count = count + 1