This guide explains Why Programs Use Loops through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A loop repeats code without copying the same statement many times. Use loops when you must process several items or perform an action until a stopping condition is met.
When You Would Use This
Print a numbered list of practice sessions.
Step-by-Step Example
for practice_day in range(1, 5):
print("Practice day", practice_day)
How the Example Works
The body runs four times, once for each number from 1 through 4. range() excludes its stop value, which is why 5 is not printed.
Example Output
Practice day 1
Practice day 2
Practice day 3
Practice day 4
Try It Yourself
Modify the loop to print the first seven practice days.
Common Beginner Mistakes
- Copy-pasting the same command rather than using a loop.
- Expecting
range(1, 5)to include 5. - Forgetting a stopping condition for a repeating task.
Key Takeaways
- A loop repeats code without copying the same statement many times.
- The body runs four times, once for each number from 1 through 4.
- Avoid this mistake: Copy-pasting the same command rather than using a loop.