Kids Coding
While Loops
while repeats until a condition is false. Use it for games that keep going.
KidsIntermediateWhile Loops
Repeat until you should stop
for repeats a known number of times. while repeats as long as a check is true.
Count down
n = 3
while n > 0:
print(n)
n = n - 1
print("Go")If you forget to change n, the loop never ends. Always make the check get closer to false.
A game-shaped loop
Keep going while lives remain. This version uses a list of guesses so it can run without typing.
Lives
lives = 3
events = ["miss", "miss", "hit"]
i = 0
while lives > 0 and i < len(events):
print("Event:", events[i])
if events[i] == "miss":
lives = lives - 1
print("Lives left:", lives)
else:
print("Safe")
i = i + 1Real life
Filling a water bottle at the tap.
You keep pouring while it is not full. Stop when it is. That is while.
Fill the bottle
ml = 0
while ml < 500:
ml = ml + 100
print("Now", ml, "ml")
print("Full. Cap on.")Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Use while to print 1, then 2, then 3.
Show solution
n = 1
while n <= 3:
print(n)
n = n + 1