Skip to content

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”.

Inputs (for input())

One value per line — read in order by input().

Output
 

Three essential parts:

  1. Start: i = 1 — the counter is set up before the loop
  2. Condition: while i <= 5: — checked before every repeat
  3. Change: i = i + 1 — the counter moves forward, otherwise the condition never becomes false!

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().

Output
 

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?”

Mission

Countdown

+10 XP

Rocket 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().

Output
 
Mission

Double-double

+15 XP

Start 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().

Output
 
Mission

Guess the number game

+20 XP

Write 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().

Output
 

🏅 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 →