Loops
Repeat work with for and while loops and recognize when a loop stops.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A for loop visits items in a sequence. range(1, 4) produces 1, 2, and 3; the stop value is excluded. A running total is a common reason to loop.
A while loop repeats while its condition remains true. Its body must eventually change something that makes the condition false. break can end a loop early when needed.
- for iterates over values
- range stop is excluded
- while needs a stopping condition
See it step by step
Read the code, predict the output, then compare it with the result.
01. Visit a range
for number in range(1, 4):
print(number * 2)2
4
6range(1, 4) provides 1, 2, and 3; the stop value 4 is excluded.
02. Accumulate a total
total = 0
for value in [2, 3, 4]:
total += value
print(total)9Each iteration adds the next list item to total. The final print runs after the loop.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
range(1, 6) produces 1 through 5. Keep total += number inside the loop, then print the final total after the loop.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
A while loop never progresses
count = 0
while count < 3:
print(count)count = 0
while count < 3:
print(count)
count += 1What happens: The condition stays true, so the loop keeps printing 0.
Update the value tested by the condition.
Expecting the stop value
for n in range(1, 4):
print(n)
# Expecting 1, 2, 3, 4for n in range(1, 5):
print(n)What happens: Only 1, 2, and 3 appear.
range excludes its stop argument.