Block 4: for Loops & range()
Repeat actions with for loops and range().
Concepts
- for item in iterable: pattern
- range(start, stop, step)
- Loop over lists and strings
- Accumulator pattern with a variable
Code Examples
range() and for loop
for i in range(5):
print(i) # 0,1,2,3,4
for i in range(2, 10, 2):
print(i) # 2,4,6,8
Accumulator pattern
numbers = [1, 2, 3, 4, 5]
total = 0
for n in numbers:
total += n
print(total) # 15
Exercise
Implement FizzBuzz from 1 to 50. Sum all even numbers from 1 to 100 using a loop.
Solution
# FizzBuzz
for i in range(1, 51):
if i % 15 == 0: print('FizzBuzz')
elif i % 3 == 0: print('Fizz')
elif i % 5 == 0: print('Buzz')
else: print(i)
# Sum evens 1-100
total = 0
for n in range(2, 101, 2):
total += n
print('Sum of evens:', total) # 2550Practice Problems
Problem 1: Print the first 10 square numbers (1, 4, 9, 16, ...)
Hint: for i in range(1, 11): print(i**2)
Problem 2: Count how many vowels are in the string 'hello world'
Hint: Loop over chars, check if in 'aeiou'
Application
Loops are fundamental for iterating over datasets, processing batches, and running simulations.
Case Study
A data pipeline loops over 1000 CSV files, reads each, cleans it, and appends to a master DataFrame. The accumulator pattern builds the final dataset.
Homework
What is the difference between range(5) and range(1,6)? Show with code.