Ask a question
while battery > 0: asks, is the battery above 0?
05LOOPS · WHILE
A while loop asks a True-or-False question before every turn. True: one more turn. False: stop.
LOOK FIRST
while battery > 0: asks, is the battery above 0?
If the answer is True, the indented lines run again.
If the answer is False, the loop ends and Python goes on.
while battery > 0:321charge me!STEP BY STEP
Something inside the loop must change, so the answer can become False.
battery = 3Start with 3 bars of battery.while battery > 0:The question. 3 > 0 is True, so a turn starts. print(battery)Shows what is in the box now: 3, then 2, then 1. battery = battery - 1Take 1 away. Without this line the answer stays True forever!print("charge me!")Runs once, when 0 > 0 is False and the loop is over.LOOK FIRST
range(3) gives exactly 3 turns. Use for when you can count the turns first.
Keep going until the question becomes False, even if you do not know how many turns.
If nothing changes, the loop never ends. If that happens, press Stop.
RUN IT
Guess first. Then run real Python and check.
steps = 0
while steps < 3:
print("step")
steps = steps + 1How many times will PyBot say step?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change 3 to 5. Run again and count the steps.
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
while battery > 0:When does a while loop ask its question?
n = 0
while n < 4:
print(n)
n = n + 1How many numbers show?
n = 1
while n < 3:
print(n)
n = n + 1Which is the last number Python shows?
battery = 0
while battery > 0:
print("go")
print("rest")How many times does go show?
lap = 1
while lap < 3:
print("run")What happens?
🍪 🍪 🍪 … ?PyBot must eat cookies until the jar is empty. It does not know how many there are. Which loop fits?
PyBot wants to count 3, 2, 1, but nothing shows. Fix the question in the while line.
3 2 1OUTPUT
Want a fresh start? Clear only this page.
Next: Python has no until word, but you can still repeat until something is done.