Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Loops?For Loops BasicsWhile Loops BasicsLoop ControlIterating ListsLoop PatternsNested LoopsDebugging LoopsBest Practices
Python/Loops/Loop Patterns

🔁 Loop Patterns — Common Solutions

Every programmer uses these patterns constantly. Master them and you'll write powerful code.


🎯 Pattern 1: Counter

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")

💡 Pattern 2: Accumulator

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!

🔍 Pattern 3: Search

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}")

📊 Pattern 4: Find Maximum/Minimum

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}")

🎨 Practical Applications

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.6

Example 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}")

🔑 Key Takeaways

PatternPurposeKey Variable
CounterCount occurrences`count += 1`
AccumulatorSum or combine`total += value`
SearchFind item`break` when found
Max/MinFind extremeCompare and update

🔗 What's Next?

Handle complex cases with Nested Loops!


Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn