The while loop
for knows in advance how many times it will repeat. But what if you don’t? In a game, “keep asking until the right answer is found” — nobody knows how many tries that will take. That’s what while is for: “as long as the condition is true — repeat”.
How while works
Section titled “How while works”Inputs (for input())
One value per line — read in order by input().
Three essential parts:
- Start:
i = 1— the counter is set up before the loop - Condition:
while i <= 5:— checked before every repeat - Change:
i = i + 1— the counter moves forward, otherwise the condition never becomes false!
⚠️ The infinite-loop trap
Section titled “⚠️ The infinite-loop trap”What happens if you forget the 3rd part? The condition stays always true and the loop never ends. Try it — don’t be afraid, our playground stops it on its own after 5 seconds:
Inputs (for input())
One value per line — read in order by input().
See that? i never gets past 5, because nothing is increasing it. On your own computer a program like this would run forever — so whenever you write a while, always ask yourself: “will this loop ever end?”
Missions
Section titled “Missions”Countdown
+10 XP ✓ CompletedRocket launch: use while to count down from 5 to 1, and after the loop ends, print Start!.
Inputs (for input())
One value per line — read in order by input().
Double-double
+15 XP ✓ CompletedStart at 1 and multiply by 2 each time: 1, 2, 4, 8… Find the first number that passes 1000. (A familiar figure will pop up! 😉)
Inputs (for input())
One value per line — read in order by input().
Guess the number game
+20 XP ✓ CompletedWrite your first real game! The secret number is 7. Keep asking with while until the player guesses it, and when they do, say You got it! 🎉. (Three of the player’s attempts are ready in the inputs: 5, 9, 7.)
Inputs (for input())
One value per line — read in order by input().
🏅 You finished this module! You’ve even written a real game now. In the next module we’ll give your program whole lists instead of single memory boxes — list and dict for keeping hundreds of pieces of data in one place. Continue →