For Loops
Master iteration with Python for loops to process collections and ranges.
Loops are essential for automating repetitive tasks in programming. The for loop in Python is elegant and powerful, allowing you to iterate over any sequence including lists, strings, and ranges. From processing data files to generating reports, for loops are used in virtually every Python application. This exercise teaches you to write efficient loops that make your code cleaner and more maintainable.
📚 Concepts & Theory
Basic For Loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using range():
# 0 to 4
for i in range(5):
print(i)
# 1 to 5
for i in range(1, 6):
print(i)
# 0, 2, 4, 6, 8 (step of 2)
for i in range(0, 10, 2):
print(i)
Looping with Index:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
Loop Control:
break- Exit the loop immediatelycontinue- Skip to next iteration
for i in range(10):
if i == 5:
break # Stop at 5
if i % 2 == 0:
continue # Skip even numbers
print(i)
Nested Loops:
for i in range(3):
for j in range(3):
print(f"({i}, {j})") 🎯 Your Challenge
Use a for loop with range() to calculate the sum of numbers from 1 to 10 (inclusive). Store the final sum in a variable called `total`.
📝 Starter Code
# Calculate sum of 1 to 10
total = 0
# Your for loop here
for i in range(1, 11):
# Add i to total
- Initialize total to 0 before the loop
- range(1, 11) gives numbers 1 through 10
- Add each number to total inside the loop
- Use total = total + i or total += i
Solution
total = 0
for i in range(1, 11):
total = total + i
# Alternative: total += i
Explanation
We initialize total to 0, then use range(1, 11) to generate numbers from 1 to 10 (11 is exclusive). Inside the loop, we add each number to total. After the loop completes, total contains the sum of all numbers (55). You can also use the shorthand += operator for addition.
⚠️ Common Mistakes to Avoid
- Using range(10) instead of range(1, 11)
- Forgetting that range end value is exclusive
- Not initializing the sum variable before the loop
- Wrong indentation inside the loop