Skip to content

Beginner · Loops: repeating work · topic 12 of 50 · 25 min

Common loop patterns

Explanation

Most loops follow a few patterns: keep a running total, count matching items, remember the biggest or smallest value, or build a new string piece by piece. They all use an accumulator, a variable set up before the loop and updated in every round. Loops can also sit inside other loops to make tables and patterns.

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.

Think of it like this: An accumulator is like a gullak, a piggy bank. It starts empty before the month begins. Every day you drop in a coin. At the end of the month you break it open and see the total. The gullak is the variable, and each coin is one round of the loop.

Running total

python
total = 0
for n in range(1, 11):
    total += n
print("Sum of 1 to 10:", total)
Start at 0, add each number. Prints Sum of 1 to 10: 55.

Counter

python
count = 0
for n in range(1, 31):
    if n % 3 == 0:
        count += 1
print("Multiples of 3 from 1 to 30:", count)
A counter adds 1 only when the condition is True. Prints 10.

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.

python
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)
Prints Biggest digit: 9 Smallest digit: 0.
Tip: Start the maximum with the first value, not with 0. If all the values are negative, like temperatures in Leh in winter, a start of 0 would wrongly stay the maximum.

Building a string

python
word = "chai"
reversed_word = ""
for ch in word:
    reversed_word = ch + reversed_word
print(reversed_word)
Each new letter goes in front, so the word comes out backwards: iahc.

Nested loops

A nested loop is a loop inside another loop. For each round of the outer loop, the inner loop runs completely.

python
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}", end="   ")
    print()
A small multiplication table. The outer loop picks the row; the inner loop fills the row. print() ends each row.
python
for row in range(1, 5):
    print("*" * row)
A star triangle: one star in row 1, two in row 2, and so on up to four.
Careful: Put the accumulator's starting value BEFORE the loop. If you write total = 0 inside the loop, it is reset in every round and you only get the last value. For multiplying, start at 1, not 0, because anything times 0 is 0.
PatternBefore the loopInside the loop
Totaltotal = 0total += value
Productresult = 1result *= value
Countercount = 0if condition: count += 1
Maximumbest = first valueif value > best: best = value
New stringtext = ""text = text + piece

Watch the lesson

Common loop patterns · 1/7

Common loop patterns

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.

python
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}")
Prints Runs: 13, Wickets: 1.

Practice (0/3 done)

Task 1 · Code · Python

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.

Task 2 · Code · Python

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.

Task 3 · Code · Python

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

Question 1

1.You want to multiply many numbers together in a loop. What should the accumulator start at?

Question 2

2.total = 0, then for i in range(1, 5): total += i. What is total?

Question 3

3.for i in range(3): for j in range(4): print("*"). How many stars are printed?

Question 4

4.Why should a maximum start with the first value instead of 0?

Question 5

5.result = "", then for ch in "abc": result = ch + result. What is result?

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.

← Previous: break, continue and loop else