Beginner · Loops: repeating work · topic 12 of 50 · 25 min
Common loop patterns
Explanation
The accumulator idea
An accumulator is a variable that collects a result while a loop runs. You give it a starting value BEFORE the loop, change it INSIDE the loop, and use it AFTER the loop. Totals, counts, maximums and new strings are all accumulators.
Running total
total = 0
for n in range(1, 11):
total += n
print("Sum of 1 to 10:", total)Counter
count = 0
for n in range(1, 31):
if n % 3 == 0:
count += 1
print("Multiples of 3 from 1 to 30:", count)Finding the biggest and smallest
To find the maximum, keep the biggest value seen so far. Start with the first value, then compare every other value with it and replace it when you find a bigger one.
marks = "47390"
best = int(marks[0])
worst = int(marks[0])
for ch in marks:
digit = int(ch)
if digit > best:
best = digit
if digit < worst:
worst = digit
print("Biggest digit:", best, "Smallest digit:", worst)Building a string
word = "chai"
reversed_word = ""
for ch in word:
reversed_word = ch + reversed_word
print(reversed_word)Nested loops
A nested loop is a loop inside another loop. For each round of the outer loop, the inner loop runs completely.
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}", end=" ")
print()for row in range(1, 5):
print("*" * row)| Pattern | Before the loop | Inside the loop |
|---|---|---|
| Total | total = 0 | total += value |
| Product | result = 1 | result *= value |
| Counter | count = 0 | if condition: count += 1 |
| Maximum | best = first value | if value > best: best = value |
| New string | text = "" | text = text + piece |
Watch the lesson
Common loop patterns · 1/7
In this lesson you will learn the loop patterns that programmers use every day.
Prefer a video by a teacher? Find free videos on “python loop patterns accumulator nested loops beginners” on YouTube ↗
In real life: Scoring an over in cricket
A scorer writes each ball of an over as one character: a digit for runs and W for a wicket. One loop with two accumulators adds up the runs and counts the wickets, just like the scoreboard at a cricket ground.
over = "1406W2"
runs = 0
wickets = 0
for ball in over:
if ball == "W":
wickets += 1
else:
runs += int(ball)
print(f"Runs: {runs}, Wickets: {wickets}")Practice (0/3 done)
The function factorial(n) should return 1 x 2 x 3 x ... x n, so factorial(5) is 120. By rule, factorial(0) is 1. The starter always returns 0. Fix the starting value of the accumulator.
Write a function largest_digit(digits) that takes a string of digits and returns the biggest digit as a number. Example: largest_digit("4729") returns 9.
Write a function star_triangle(n) that returns (not prints) a triangle of n rows as one string: row 1 has 1 star, row 2 has 2 stars, and so on. Rows are separated by "\n" (a new line), with no "\n" after the last row. Use a nested loop or "*" * row. Example: star_triangle(3) returns "*\n**\n***".
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.