Python While Loops & Iteration
A while loop is like hitting the "Snooze" button: as long as you are still sleepy, the alarm keeps ringing. The golden rule: ALWAYS remember to update your condition variable inside the loop, or your code will loop forever until your browser times out.
"Think of pouring water into a glass. WHILE the glass is not full, you keep pouring. As soon as the water reaches the brim, you stop. If you never check the level, water spills everywhere (an infinite loop)."
Deep Dive: How It Works
The while loop repeatedly executes its indented block as long as its condition evaluates to True.
Before every single iteration, Python checks the condition. If it is True, it runs the block. If it is False, the loop terminates immediately and Python moves to the code below.
Infinite Loops: If the condition never becomes False (for example, if you forget to increment your counter), the loop will run endlessly. In ZenCompiler, sandboxes have automatic 15-second execution timeouts to protect against infinite loops.
Loop Control Keywords: "break" exits the loop immediately, while "continue" skips the rest of the current iteration and jumps directly to the next check.
Syntax Blueprint
count = 0
while count < 5:
print(count)
count += 1 # Crucial update stepCheck condition, run block, update variable so condition eventually becomes False.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting to increment the counter: count += 1Why it happens: If count stays at 0, 0 < 5 is ALWAYS True, freezing execution.
How to fix: Double-check that your loop has a clear progress step towards termination.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Count from 1 to 3 with a while loop
Initialize i = 1.
Use a while loop to print numbers 1, 2, and 3, incrementing i by 1 each time.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.