Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Change the flow
EXPERIMENT 09 / 101

Keep going. Know when to stop..

Repeat while a condition holds, then leave the loop deliberately.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

A while loop checks a condition before every iteration. Its body runs while that condition is truthy. It is useful when you do not know the number of repetitions in advance. A changing value, new input, or a break statement must provide a way to finish.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

while_loops.py
attempts = 0

while attempts < 3:
    attempts += 1
    print(f"Attempt {attempts}")

print("Time for a different approach")
↳ EXPECTED OUTPUT
Attempt 1
Attempt 2
Attempt 3
Time for a different approach

03 Under the hood

  1. 1

    The loop begins with attempts at zero. The condition is checked before the first print.

  2. 2

    Each iteration increments the counter. When it becomes 3, the next condition check is False.

  3. 3

    break exits the nearest loop immediately. continue skips the rest of the current iteration, returning to the next condition check. Keep updates before continue when they are needed for termination.

04 Your turn, builder

A SMALL MISSION

Count down from 3 to 1, then print "Go!".

Reveal one possible solution +
one_possible_solution.py
count = 3
while count > 0:
    print(count)
    count -= 1
print("Go!")

05 Check your signal

QUICK SIGNAL CHECK

When is a while condition checked?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.