While Loops
Repeat code while a condition is true. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Countdown TimerStudy Material
Read the full lesson
Breaking the linear path
Up until now, your code runs like a simple waterfall: it starts at line 1, executes line 2, line 3, and then finishes.
But what if you need to repeat a task? If you need to print "Hello" ten thousand times, you do not want to write 10,000 print statements.
You need a loop.
The while loop
A while loop runs a block of code over and over again as long as a condition remains True.
pythoncountdown = 5 while countdown > 0: print(f"T-minus {countdown}...") countdown = countdown - 1 print("Blastoff!")
Here is exactly how Python reads this:
- Is
countdown > 0? Yes (it's 5). Print, and subtract 1. - Is
countdown > 0? Yes (it's 4). Print, and subtract 1. - ...
- Is
countdown > 0? Yes (it's 1). Print, and subtract 1. - Is
countdown > 0? False (it's 0).
The moment the condition becomes False, the loop breaks and Python drops down to print "Blastoff!".
The danger of the Infinite Loop
If you forget to update the variable inside the loop (like forgetting countdown = countdown - 1), the condition will never become False.
pythoncountdown = 5 while countdown > 0: print("This will run forever!") # Missing subtraction here!
This creates an Infinite Loop. Your program will just print that line millions of times until you physically force-quit it or your computer runs out of memory.
Always make sure your loop has a clear, guaranteed way to finish!
What this lesson should give you
After this lesson, you should understand how to:
- write a
whileloop that repeats an action - establish a condition that controls when the loop stops
- update variables inside the loop to avoid an infinite loop
- understand the order of execution as Python flows backward up to test the condition again
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Countdown Timer
Complete the "Countdown Timer" exercise.
Guess the Number
Complete the "Guess the Number" exercise.
Sum Digits
Complete the "Sum Digits" exercise.
Login Retry (3 Attempts)
Complete the "Login Retry (3 Attempts)" exercise.
Sentinel Loop (quit to exit)
Complete the "Sentinel Loop (quit to exit)" exercise.