
Python
Every programmer uses these patterns constantly. Master them and you'll write powerful code.
Count how many times something happens:
numbers = [1, 2, 3, 4, 5]
count = 0
for number in numbers:
if number > 2:
count = count + 1
print(f"Found {count} numbers greater than 2")Sum up or combine values:
# Sum all numbers
total = 0
for number in [1, 2, 3, 4, 5]:
total = total + number
print(f"Sum: {total}") # 15
# Combine strings
message = ""
for word in ["Hello", "World", "!"]:
message = message + word
print(message) # HelloWorld!Find the first item that matches:
numbers = [1, 3, 5, 8, 9]
target = 8
found = False
for number in numbers:
if number == target:
found = True
break
if found:
print(f"Found {target}")
else:
print(f"Did not find {target}")scores = [78, 92, 85, 88, 95]
# Find maximum
max_score = scores[0]
for score in scores:
if score > max_score:
max_score = score
print(f"Highest: {max_score}")
# Find minimum
min_score = scores[0]
for score in scores:
if score < min_score:
min_score = score
print(f"Lowest: {min_score}")Example 1: Average calculator
grades = [85, 92, 78, 88, 95]
total = 0
for grade in grades:
total = total + grade
average = total / len(grades)
print(f"Average: {average}") # 87.6Example 2: Filter and count
items = ["apple", "apricot", "banana", "avocado"]
a_count = 0
for item in items:
if item[0] == "a":
a_count = a_count + 1
print(f"Items starting with 'a': {a_count}")| Pattern | Purpose | Key Variable |
|---|---|---|
| Counter | Count occurrences | `count += 1` |
| Accumulator | Sum or combine | `total += value` |
| Search | Find item | `break` when found |
| Max/Min | Find extreme | Compare and update |
Handle complex cases with Nested Loops!
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward