Course outline · 0% complete

0/27 lessons0%

Course overview →

The while loop

lesson 5-2 · ~10 min · 16/27

Loop while a condition holds

A for loop is for "do this N times", but often you cannot know N in advance: keep asking until the user types a valid answer, keep downloading until the file ends, keep the game running until someone wins. That "repeat for as long as some condition holds" shape is what the second kind of loop exists for. A while loop is for "keep going as long as a condition is True":

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Liftoff!")

Before every iteration, Python checks the condition count > 0 (a comparison from lesson 4-1). True? Run the body. False? Skip past the loop and continue below it.

The line count = count - 1 is the update pattern from lesson 3-2, and it is what makes the loop finish. Without it, count stays 3, the condition stays True, and the program loops forever. That is called an infinite loop, and it is the classic while-loop bug (the sandbox will cut it off with a timeout, your own computer would just spin). Every while loop needs something in the body that moves it toward False.

Code exercise · python

Run the countdown. Then trace it by hand: write down the value of count at each condition check.

Quiz

What is wrong with this loop? n = 5 while n > 0: print(n)

Code exercise · python

Your turn. Start n at 1. Using a while loop, print n and then double it (n = n * 2), as long as n <= 16. Expected output: 1, 2, 4, 8, 16, one per line.