Browser lab18 min+60 XP

while loops

Repeat code while something is true. Countdowns, retries and game loops.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

A while loop repeats as long as its condition stays True.

Key words
countdown = 5countdown > 0 ?print(countdown)countdown -= 1print("Lift off!")TruerepeatFalse
The loop checks the condition, runs the body, and goes round again.

A while loop repeats its indented block as long as its condition is true. Python checks the condition, runs the block, checks again, and so on. When the condition becomes false, the loop ends and the program carries on below it.

Something inside the loop must change, or the condition stays true forever. That is an infinite loop. In this lab a safety switch stops programs after 6 seconds, so you cannot break anything.

while loops are perfect when you do not know in advance how many times to repeat, like "keep asking until the password is right".

Real life linkA phone keeps asking for your passcode while it is wrong. It does not know in advance how many tries you will need, so it uses a while loop.
Example code
countdown = 5
while countdown > 0:
    print(countdown)
    countdown = countdown - 1
print("Lift off!")
TASK 2

Try it yourself

+10 XP

Keep asking Password: until the user types letmein. Then print Welcome back.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What do we call a loop whose condition never becomes false?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Number guessing game

+20 XP

The secret number is 7. Keep asking Guess: until the player gets it right. After each wrong guess print Too low or Too high. When they win, print Correct! You took 3 guesses (with the real count).

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.