Loops in Python
Overview
Loops let you run a block of code repeatedly, which saves time and avoids duplicate statements.
Learning Objectives
- Iterate over sequences of items using for loops.
- Repeat code blocks based on conditions using while loops.
- Use the range() helper to iterate a specific number of times.
Concept Explanation
A for loop goes through items in a collection (like a list or string) one-by-one. A while loop keeps running as long as a specified condition is True. We must change the condition inside while loops, or they will run forever.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
# Loop three times
for i in range(3):
print(f'Loop index: {i}')
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Print values of scores list
scores = [88, 92, 79]
total = 0
for score in scores:
total += score
print(f'Total score: {total}')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Process task list items sequentially
pending_tasks = ['clean', 'verify', 'upload']
while pending_tasks:
current = pending_tasks.pop(0) # Take the first task
print(f'Completed task: {current}')
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Evaluate Loop Condition → True? Run Block → Update iteration status → Repeat check
Common Mistakes
Review these common pitfalls when working with this topic:
- Forgetting to update counter variables inside while loops, causing infinite loops.
- Modifying the size of a list directly while iterating over it.
- Using range(len(items)) to loop list elements instead of looping items directly.
- Indenting code statements incorrectly inside loop bodies.
Best Practices
Enforce these Pythonic best practices in your codebase:
for i in range(len(fruits)):
print(fruits[i]) # Unnecessary index lookups
for fruit in fruits:
print(fruit) # Clear direct iteration
Quick Revision
Use these key summaries for last-minute revision:
- for loops iterate over collections and ranges.
- while loops repeat statements while checks stay True.
- range(n) generates numbers from 0 up to n-1.
- Change loop variables inside while loops to prevent infinite loops.
- Looping directly over list items is cleaner than indexing.