Lessons › coding and computer science · taught by Leo
For loops and while loops: when to use each
Learn how for loops count fixed repeats and while loops run until a condition changes, plus how to avoid infinite loops.
Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.appWhy loops save repeated work
When code has to repeat, a loop saves you from writing the same lines again and again.
The big idea is simple: one block of code can run many times.
You choose a loop when the pattern is repeated work.
For loops count exact repeats
A for loop is best when you know how many times you want to repeat.
The counter moves through a planned set of values, then the loop ends.
So for loops are great for counting, lists, and fixed repeats.
Predict the loop type
You know you want to print a message 5 times. Which loop fits best?
- for loop
- while loop
Show answer
for loop: Yes. A for loop is a natural fit when the number of repeats is already known.
A for loop counted step by step
Let’s watch a tiny for loop with three repeats.
The range gives the counter values 0, 1, and 2.
Each time through, the same block runs once.
What happens next?
In for i in range(4), what should you expect from i?
- 0, 1, 2, 3
- 1, 2, 3, 4
- 0, 1, 2, 3, 4
Show answer
0, 1, 2, 3: Correct. range(4) gives four values starting at 0.
Why while loops need a test
A while loop keeps going only while a condition is true.
A while loop is for repeating until something changes.
You do not usually know the exact number of repeats at the start.
That is why the condition gets checked again and again.
While loops repeat until a stop
A while loop starts by checking a condition.
If the condition is true, the block runs and then the test happens again.
When the condition becomes false, the loop stops.
Why updating the variable matters
This is the most important while-loop habit: change something inside the loop.
That update pushes the condition toward false.
Without it, the loop may never stop.
Predict the missing move
You wrote while x < 3:. What is the most important thing to do inside the loop?
- Change x so it can reach 3
- Leave x the same
- Delete the condition
Show answer
Change x so it can reach 3: Exactly. The loop needs an update so the condition can eventually become false.
Common mistake: infinite loops
The biggest while-loop mistake is forgetting the update.
Then the condition stays true forever, so the loop never ends.
Always ask: what changes each time through?
Your turn: choose the loop
You want to keep asking for a password until the answer is correct. Which loop fits best?
- for loop
- while loop
Show answer
while loop: Good choice. You do not know how many tries it will take, so while is the better fit.
Loop cheat sheet
Use for when the repeat count is known.
Use while when you wait for a condition to change.
And always make sure a while loop has a way to stop.