←Previous page

05LOOPS · WHILE

Repeat while it is true.

A while loop asks a True-or-False question before every turn. True: one more turn. False: stop.

LOOK FIRST

while asks before every turn.

Ask a question

while battery > 0: asks, is the battery above 0?

True: one more turn

If the answer is True, the indented lines run again.

False: stop

If the answer is False, the loop ends and Python goes on.

while battery > 0:321charge me!

STEP BY STEP

Watch the question change.

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

for or while?

for: you know how many

range(3) gives exactly 3 turns. Use for when you can count the turns first.

while: you know when to stop

Keep going until the question becomes False, even if you do not know how many turns.

Change the box

If nothing changes, the loop never ends. If that happens, press Stop.

RUN IT

Help PyBot walk a few steps.

Guess first. Then run real Python and check.

1

Guess the result

steps = 0 while steps < 3: print("step") steps = steps + 1

How many times will PyBot say step?

steps.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide ♥

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

Ask, repeat, stop.

Try each tiny question. A wrong answer becomes something to review.

0Completed
8Not tried
0Review
01

When does it ask?

while battery > 0:

When does a while loop ask its question?

02

Count the turns

n = 0 while n < 4: print(n) n = n + 1

How many numbers show?

03

The last number

n = 1 while n < 3: print(n) n = n + 1

Which is the last number Python shows?

04

Zero turns

battery = 0 while battery > 0: print("go") print("rest")

How many times does go show?

05

Something is missing

lap = 1 while lap < 3: print("run")

What happens?

06

Pick the loop

🍪 🍪 🍪 … ?

PyBot must eat cookies until the jar is empty. It does not know how many there are. Which loop fits?

07

Fix PyBot's code

PyBot wants to count 3, 2, 1, but nothing shows. Fix the question in the while line.

Goal output
3
2
1
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

A while loop repeats as long as its question is True.

Next: Python has no until word, but you can still repeat until something is done.