Repeating with while
In Phase I you used for loops to repeat a fixed number of times. But sometimes you don’t know how many times — you want to keep going until something happens. “Keep asking until the player guesses right.” “Keep going until the countdown hits zero.” That’s a while loop.
while: repeat as long as it’s true
A while loop checks a yes/no test, and repeats its indented lines as long as the test is True:
while some_test:
# repeat while the test stays true
Here’s a countdown. Each time around, n gets one smaller, until it’s no longer greater than 0:
The key is that something inside the loop changes the test (n = n - 1). Without that, the test would stay True forever and the loop would never stop!
Try it 🎯
- Change
n = 5ton = 10. - Count up instead: start
n = 1, loopwhile n <= 5, printn, thenn = n + 1.
A real game: guess the number
This is the classic. The computer picks a secret number, and the loop keeps asking until you guess it — giving “higher” or “lower” hints along the way:
Look at how it works: the loop runs while your guess isn’t the secret. Each wrong guess triggers a hint, and the box pops up again. The moment guess == secret, the test becomes False and the loop ends. Play a few rounds!
Predict it 🔮
How many numbers does this print? Trace it before running:
(Three lines: loop 3, loop 2, loop 1. When n reaches 0 the test n > 0 is False, so it stops.)
Fix the bug 🐞
This countdown is supposed to print 5 down to 1, but it prints an extra 0 at the end. Look at the test:
(n >= 0 keeps going while n is 0 too. To stop at 1, use while n > 0:.)
⚠️ One rule with
while: make sure something inside the loop moves it toward stopping (liken = n - 1). If nothing changes, the loop runs forever!
Your mission 🚀
Make a “password gate”: keep asking for the password until the user types "open". Use a while loop that repeats while the answer is not "open":
Run it, type some wrong words, then type open. Then try changing the magic word to your own secret.
What you learned today
- A
whileloop repeats as long as its test is True. - Something inside the loop must move it toward stopping.
whileis perfect when you don’t know the number of repeats ahead of time — like guessing games and “keep asking until…”.
Next time we tackle lists — a way to hold many things at once, like a whole list of scores or names. It’s the door to working with data. 📋
Comments