Card 7: While Loops
Module 3: Power of Repeating
1 The Hook
Have you ever seen a Loading Spinner that never stops?
That's a Loop. Computers are great at doing the same thing over and over
again without getting bored.
We use a while loop to keep going as long as a condition
is True.
2 Worked Example
A classic Countdown.
PREDICT
We change the math. What happens?
while n < 10:
print(n)
n = n + 5
Input Required
Interactive Editor
🥉 Count UP
The current code counts down.
1. Change n = 1.
2. Change condition to while n <= 10.
3. Change math to n = n + 1.
🥈 Infinite Loop!
This code runs forever because we forgot something important inside the loop.
Add the line to decrease n so the loop stops.
🥇 Guess the Number
1. Create a variable secret = 7.
2. Create a variable guess = 0.
3. Make a loop: while guess != secret.
4. Inside the loop, ask user to input("Guess: ") (remember int()).
5. After loop, print "You won!".