python · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A loop keeps going while something is True.
Think of knocking on a door. You keep knocking while nobody answers. You do not know how many knocks it will take. A while loop works the same way: it repeats as long as its condition is True.
Most while loops use a variable that counts, like count below. Create it before the loop. Check it in the condition. Change it inside the loop, so the condition turns False one day and the loop ends.
Forget to change it and the condition stays True forever. That is an : the program goes round and round and never moves on. It is a common slip, and the fix is always the same: change the variable inside the loop.
count = 1
while count <= 3:
print("Knock knock", count)
count = count + 1
print("Who's there?") Delete the last indented line and count stays 1 forever, so the knocking would never stop.
guess first
How many times will it say Nom?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
cookies = 3
while cookies > 0:
print("Nom")
cookies = cookies - 1
print("All gone!")
your turn
Your turn. Launch your own rocket.
Type a starting number from 3 to 10 in the first blank and your own launch shout in the second. Then press run.
fix it
This bouncy loop crashes before it starts. Can you fix it?
- Read the error. It is a NameError. Which name has Python never seen?
- The loop checks jumps < 3 straight away, but no box called jumps exists yet.
- Add jumps = 0 as a new first line, above the while line.
nailed it
you built a loop that knows when to stop. :D
- A
whileloop repeats while its condition is True. - Create the counting variable before the loop. Change it inside.
- If nothing changes, you get an infinite loop.
new words in your collection
- while
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.