Mastering for Loops

For loops automate repetitive tasks by iterating over sequences. Combined with range(), they become powerful tools for numerical operations and data processing.

Loop Fundamentals

# Basic range loop
for i in range(3):
print(i) # 0, 1, 2
0\n1\n2
Key points:
  • range(stop) generates 0 to stop-1
  • range(start, stop) creates start to stop-1
  • Always increments by 1

Accumulator Pattern

# Calculate product
product = 1
for n in [2, 3, 4]:
product *= n
print(product) # 24
24

This pattern:

  • Initializes an accumulator variable
  • Modifies it each iteration
  • Returns final accumulated value

Common Errors

# Off-by-one errors
range(5) # 0-4, not 1-5
# Forgetting to increment
total = 0
for num in nums: pass # total remains 0

Practical Use: Shopping Cart

prices = [4.99, 9.99, 2.49]
total = 0.0
for price in prices:
total += price
print(f"Total: ${total:.2f}")
Total: $17.47

Your Task: Number Summation

Calculate the sum of numbers 1 through 5:

  1. Initialize total to 0
  2. Use range(1, 6) in a for loop
  3. Add each number to total
  4. Final result should be 15

Remember: Range is exclusive of the upper bound!

Section 1/5Loop Fundamentals

Loop Fundamentals

Explore this concept

Mastering for Loops

For loops automate repetitive tasks by iterating over sequences. Combined with range(), they become powerful tools for numerical operations and data processing.

Loop Fundamentals

# Basic range loop
for i in range(3):
print(i) # 0, 1, 2
0\n1\n2
Key points:
  • range(stop) generates 0 to stop-1
  • range(start, stop) creates start to stop-1
  • Always increments by 1

Output:

Click "Check" to run your code.