while loops
Repeat code while something is true. Countdowns, retries and game loops.
Code runs right here in your browser. Nothing to install.
Learn it
A while loop repeats as long as its condition stays True.
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".
countdown = 5 while countdown > 0: print(countdown) countdown = countdown - 1 print("Lift off!")
Try it yourself
+10 XPKeep 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.
Capture the flag
+10 XPWhat 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.
Number guessing game
+20 XPThe 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.