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.

n = 5 # Start at 5
while n > 0: # Keep going while n is passed 0
print(n)
n = n - 1 # DECREASE n (Important!)
print("Blastoff!")

PREDICT

We change the math. What happens?

n = 1
while n < 10:
  print(n)
  n = n + 5

Interactive Editor

> _
BRONZE (MODIFY)

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

> _
SILVER (FIX)

🥈 Infinite Loop!

This code runs forever because we forgot something important inside the loop.
Add the line to decrease n so the loop stops.

> _
GOLD (MAKE)

🥇 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!".

> _