While Loops and Animation¶
Summary¶
while loops keep running as long as a condition is true — perfect for games
and animations. This chapter covers while, how to stop loops with break,
skip iterations with continue, the else clause on loops, infinite-loop
dangers, countdown loops, and the time module. You'll finish with a
real animated turtle drawing that moves by itself.
Concepts Covered¶
This chapter covers the following 10 concepts from the learning graph:
- while Loop
- break Statement
- continue Statement
- else Clause on Loops
- Nested Loops
- Infinite Loops to Avoid
- Countdown Loop
- time Module Overview
- time.sleep()
- Animation with Turtle Loops
Prerequisites¶
This chapter builds on concepts from:
- Chapter 5: Drawing with Turtle Graphics
- Chapter 7: For Loops and Drawing Shapes
- Chapter 9: Making Decisions with If/Else
By the end of this lesson you'll be able to:
- Write a
whileloop that runs as long as a condition isTrue - Use
breakto exit a loop early andcontinueto skip an iteration - Explain why infinite loops happen and how to avoid them
- Build an animated turtle spiral that grows step by step using a
whileloop
The for loop you learned in Chapter 7 is perfect when you know exactly how many times to repeat — for i in range(10) repeats exactly ten times.
But what if you don't know in advance when to stop?
What if you want to keep counting down until a rocket launches, or keep drawing until the turtle reaches the edge of the screen?
That is when you need a while loop.
Welcome to Chapter 10!
The while loop is where programs come alive — it's the engine behind games, animations, and anything that runs until something changes. By the end of this chapter, Monty the turtle will be drawing all by himself! Let's code it together!
The while Loop¶
A while loop repeats its body as long as a condition is True.
The structure looks like an if statement, but instead of running once, it keeps running:
1 2 3 4 5 | |
Here is what happens step by step:
| Step | count value |
Condition count > 0 |
Action |
|---|---|---|---|
| 1 | 5 | True | print 5, count becomes 4 |
| 2 | 4 | True | print 4, count becomes 3 |
| 3 | 3 | True | print 3, count becomes 2 |
| 4 | 2 | True | print 2, count becomes 1 |
| 5 | 1 | True | print 1, count becomes 0 |
| 6 | 0 | False | loop ends, print "Liftoff!" |
The loop runs exactly as long as the condition stays True.
The moment it becomes False, Python exits the loop and continues with the next line.
Scratch Bridge
In Scratch, the Repeat Until block keeps running its contents until a condition becomes true. Python's while loop is the same idea — except the condition is checked at the start of each trip: the loop continues while the condition is True and stops the moment it becomes False.
Before you run the countdown program, think about what it will print.
What Do You Think Will Happen?
The variable count starts at 5. The loop prints count and then subtracts 1 each trip.
How many lines do you think the program will print before "Liftoff!" appears?
Will it print the number 0? Make your guess — then click Run!
Try It Now¶
Edit the code below and click Run to see the result.
Were you right? The loop prints 5, 4, 3, 2, 1 — five lines — and then "Liftoff!".
The number 0 is not printed because the condition count > 0 is checked before each trip.
When count is 0, the condition is False, so the loop ends immediately.
Infinite Loops to Avoid¶
An infinite loop is a while loop whose condition never becomes False.
The program runs forever (until you force-quit it):
1 2 3 | |
Infinite loops happen when you forget to change the variable that the condition depends on.
The most common cause: forgetting count -= 1 inside the loop.
1 2 3 4 | |
How to fix it: Every while loop needs at least one line inside it that eventually makes the condition False.
Always double-check: "What changes inside this loop to eventually stop it?"
See It: Check, Run, Check Again¶
A while loop has a rhythm: check the condition, run the body, jump back, check again. The stepper below stamps a True or False verdict every time the condition is checked. Before you click, predict: for a countdown starting at 3, how many times does the body run — and how many times is the condition checked? (They are not the same number!)
Explore the While-Loop Stepper MicroSim
Then pick the Infinite Bug program — it is the exact missing-decrement bug from above, running in a safe cage. Watch the trip odometer spin and the condition stamp True, True, True... forever. Skulpt protects you from this in the labs, but real Python will not!
The break Statement¶
break exits a loop immediately, even if the condition is still True.
It's useful when you want to stop based on something that happens inside the loop:
1 2 3 4 5 6 7 | |
This countdown stops at 7 and never reaches 6 or below — the break jumps out of the loop entirely.
The continue Statement¶
continue skips the rest of the current trip through the loop and jumps straight to the next check of the condition.
Use it to skip certain values without stopping the whole loop:
1 2 3 4 5 6 | |
Think of break as "exit the loop entirely" and continue as "skip this trip and try again."
The else Clause on Loops¶
Python has an unusual feature: you can add an else clause to a while loop.
The else block runs only if the loop ended naturally (condition became False) — not if it ended via break:
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 | |
The else on a loop is rare in practice, but it's a clean way to handle the "search succeeded / search failed" pattern.
Nested Loops¶
A nested loop is a loop inside another loop. The inner loop runs completely for every single trip of the outer loop:
1 2 3 4 | |
This prints a 3-row by 4-column grid of stars.
The inner for col in range(4) completes four trips for every single trip of for row in range(3).
Nested loops are powerful for drawing grids, tables, and 2D patterns — and you will use them more in later chapters.
The time Module¶
Python's built-in time module lets your program interact with the clock.
Before using it, you import it like any other module:
1 | |
The most useful function for animation is time.sleep(seconds) — it pauses the program for the given number of seconds (decimals are allowed):
1 2 3 4 | |
time.sleep() is how you control the speed of animations: pause for 0.05 seconds between each frame to get roughly 20 frames per second.
time.sleep() in the Browser
In a real Python program on your computer, time.sleep() pauses the program smoothly. In the Skulpt browser labs, very long sleep times may cause the page to pause for a moment. Keep time.sleep() values small (0.05–0.2 seconds) in the labs, and use larger values only when running Python on your own machine.
Animation with Turtle Loops¶
Combine a while loop with the turtle and time.sleep() to create a simple animation.
The key idea: draw one small step, pause briefly, draw the next step, pause again — and repeat.
The program below draws a growing spiral. Each time through the loop, the step length increases, so the spiral gets bigger on every trip.
Your Turn — Fix the Growing Spiral
The program below has a bug: the spiral never grows because step never changes inside the loop.
Add one line inside the loop body to increase step by 5 on every trip.
Hint: use step += 5. Watch the spiral grow as you run it!
Once the spiral appears, notice how the while step < 150 condition automatically stops the loop when the spiral is big enough — no manual counting needed!
Experiments¶
Try these changes to the programs above. For each one, predict what will happen first, then run it to check!
- In the countdown lab, change
count = 5tocount = 10. You'll know it worked when the countdown prints 10 numbers before "Liftoff!". - Change
while count > 0towhile count > 3. You'll know it worked when the countdown stops at 4, not 1. - In the spiral lab, change
t.right(45)tot.right(90). You'll know it worked when you see a square spiral instead of a diagonal one. - Change
t.right(45)tot.right(91). You'll know it worked when you see a slowly rotating spiral with gaps between the lines. - Add
t.pencolor("blue")before thewhileloop, then inside the loop addif step > 80: t.pencolor("red"). You'll know it worked when the inner part of the spiral draws blue and the outer part draws red.
Great Work!
You've mastered the while loop — Python's engine for open-ended repetition! You know how to stop loops with break, skip steps with continue, use the time module, and build animations that grow step by step. Games, simulations, and interactive programs all run on exactly this kind of loop. Let's keep coding it together!