Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Loop Patterns & Exercises
Common loop patterns - accumulation, filtering, counting, searching. These patterns appear in almost every Python program. Practice them to build muscle memory.
Common Loop Patterns
# PATTERN 1: Accumulation (summing)
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # 150
# PATTERN 2: Counting
text = "hello world"
vowel_count = 0
for char in text:
if char in "aeiou":
vowel_count += 1
print(f"Vowels: {vowel_count}") # 3
# PATTERN 3: Filtering
ages = [12, 25, 8, 30, 16, 22, 14]
adults = []
for age in ages:
if age >= 18:
adults.append(age)
print(f"Adults: {adults}") # [25, 30, 22]
# PATTERN 4: Maximum / Minimum
scores = [72, 95, 88, 64, 91]
max_score = scores[0]
for score in scores:
if score > max_score:
max_score = score
print(f"Highest score: {max_score}") # 95
# PATTERN 5: String building
words = ["Python", "is", "awesome"]
sentence = ""
for word in words:
sentence += word + " "
print(sentence.strip())Try It Yourself: FizzBuzz
Tip
Tip
These loop patterns (accumulation, counting, filtering, max/min) appear in 90% of Python programs. Master them for any coding challenge.
for loops for known counts, while loops until a condition is met
Common Mistake
Warning
Building strings with += in a loop is slow. Each += creates a new string. Use ''.join(list) instead for performance.
Practice Task
Note
(1) Find the max value without max(). (2) Count words starting with a vowel. (3) Build FizzBuzz for 1-50. (4) Filter positives from a list.