Press ▶ Run to see what your program does.
Lesson 37: while loops
Level 5, Python Thinks and Repeats. Repeat until the test is False, and stop a loop that never ends. The new word: while loop. It follows lesson 36, for loops. Next comes lesson 38, Lists.
What the lesson explains
As long as it is true. A while loop repeats until its test turns False.
A countdown. count goes down by one each time, so the loop ends. On the card: while count > 0:
What you do first
Count down from 5. Count down from 5, then Lift off!. The editor opens with: count = 3 / while count > 0: / print(count) / count = count - 1 / print("Lift off!"). One way to write it: count = 5 / while count > 0: / print(count) / count = count - 1 / print("Lift off!"). It prints: 5 / 4 / 3 / 2 / 1 / Lift off!.
The code on the screen
A countdown. The editor shows 5 lines: count = 3 / while count > 0: / print(count) / count = count - 1 / print("Lift off!"). Run it, and it prints "3", "2", "1", "Lift off!".
What you practise
Try it, "Count down from 5": Count down from 5, then Lift off!. The editor opens with: count = 3 / while count > 0: / print(count) / count = count - 1 / print("Lift off!"). One way to write it: count = 5 / while count > 0: / print(count) / count = count - 1 / print("Lift off!"). It prints: 5 / 4 / 3 / 2 / 1 / Lift off!.
Fix it, "A loop that never stops": Make the loop stop after 3. The editor opens with: n = 1 / while n <= 3: / print(n). One way to write it: n = 1 / while n <= 3: / print(n) / n = n + 1. It prints: 1 / 2 / 3.
Challenge, "Keep asking": Ask until the password is right. The editor opens with: word = "". One way to write it: word = "" / while word != "open": / word = input("Password? ") / print("Come in!"). Answer its questions with sesame, open. It prints: Password? sesame / Password? open / Come in!.
What PlayBuddy and PlayType say
PlayBuddy: "This loop keeps going as long as its test is true."
PlayType: "Make sure something changes each time, or the loop never stops!"
Help in every lesson
Everything happens on a pretend computer in your browser, so nothing touches your real files. PlayBuddy and PlayType stand beside the board, cheer you on and say when it is your turn.
A green ring shows where to click the first time. After that you do it on your own, and if you slip twice the ring comes back.
Stars
The lesson has 3 things to do. Up to one slip in ten gives three stars, up to one in four gives two, and finishing always gives at least one. Stars and progress are saved in this browser only; there is no account.
About DayOneCode
DayOneCode is an independent learning site, not affiliated with or endorsed by Anthropic. Claude and Claude Code are trademarks of Anthropic.