Keep going. Know when to stop..
Repeat while a condition holds, then leave the loop deliberately.
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.
attempts = 0
while attempts < 3:
attempts += 1
print(f"Attempt {attempts}")
print("Time for a different approach")Attempt 1 Attempt 2 Attempt 3 Time for a different approach
03 Under the hood
- 1
The loop begins with attempts at zero. The condition is checked before the first print.
- 2
Each iteration increments the counter. When it becomes 3, the next condition check is False.
- 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
Count down from 3 to 1, then print "Go!".
Reveal one possible solution +
count = 3
while count > 0:
print(count)
count -= 1
print("Go!")05 Check your signal
When is a while condition checked?
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 ↗.