Python lesson 17
While Loops. Keep Going Until
A for loop counts. A while loop waits for something to happen.
Repeat Until Something Changes
A for loop needs to know how many times to repeat before it starts. A while loop does not. It checks a question at the top of every lap, and keeps looping for as long as the answer is True.
fuel = 3
while fuel > 0: # ask the question
print(fuel)
fuel = fuel - 1 # change the answer
print("Lift off!")
fuel = 3
while fuel > 0:
print(fuel)
fuel = fuel - 1
print("Lift off!")
How Many Laps?
lives = 2
while lives > 0:
print("Try again")
lives = lives - 1
Build the Loop
Watch It Run
Click Run. Watch the number shrink until the loop gives up.
fuel = 5
while fuel > 0:
print("Fuel:", fuel)
fuel = fuel - 1
print("Lift off!")
Double It Until It Passes 100
Start at 1 and keep doubling until the number is bigger than 100. Change the starting number and see what happens.
number = 1
while number <= 100:
print(number)
number = number * 2
print("Passed 100 with", number)
Guessing Game
A secret number, and a guesser that creeps up one at a time. Change the secret and run again.
secret = 7
guess = 1
while guess != secret:
print("Guessing", guess)
guess = guess + 1
print("Found it! The secret was", secret)
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.