LESSON 15 · BEGINNER4 min read

Loop drills and patterns

Build fluency with nested loops, accumulators, prime tests, and formatted output by writing the classic loop exercises properly.

Python 3.12+Free to readModule 3 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Use nested loops to produce rows and columns.
  • Accumulate sums and products without resetting the result.
  • Write a prime test with a clear stopping rule.
  • Format repeated output with alignment and explicit separators.

01Nested loops describe rows and columns

A nested loop places one repetition inside another. The outer loop usually selects a row, and the inner loop produces the columns within that row. The inner loop completes all of its iterations for each single outer iteration. Trace the row number and column number together, or the output will feel arbitrary.

Many patterns do not need a nested loop at all. A row of stars is a string repeated a known number of times: '*' * row. Reach for the simpler expression first, then use nested loops when each position depends on both coordinates.

star_rows.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Accumulate with a purpose

An accumulator carries a partial result from one iteration to the next. Initialize it before the loop, update it inside, and use it after. A sum starts at zero; a product starts at one. If initialization happens inside the loop, each iteration discards the work that came before.

Write the update in words before writing the operator. For a factorial, the new product is the old product times the current number. For a sum of the first n natural numbers, the new total is the old total plus the current number. The words reveal whether the accumulator belongs outside the loop.

accumulators.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Search with a clear stopping rule

A prime test asks whether any integer from 2 through the square root divides the candidate. Once a divisor is found, the answer is known and the loop can return immediately. If the loop finishes without finding one, the number is prime. The stopping rule is part of the algorithm, not an optimization afterthought.

Use pass when a block is syntactically required but you intentionally have nothing to do yet. pass is not a comment and it is not a silent error handler. A loop that is supposed to search should return or raise a definite result, not fall through without saying what happened.

prime_check.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Format repetition for humans

print adds a newline by default. The end argument changes what is written after each call, and sep controls the separator between multiple arguments. Use end='' when you are assembling a line in pieces, then call print() once to finish the line. This avoids trailing spaces and makes output easier to compare.

Format specifications align numbers so a table remains readable: f'{value:>3}' reserves three character positions and right-aligns the value. Use a width large enough for the biggest result, and test the table with a boundary value. A table that looks aligned for 1 through 3 but breaks at 100 is not finished.

aligned_table.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Nested loops pair an outer row with an inner column.
  • Accumulators belong before the loop and must be updated on every relevant path.
  • Formatting is part of the result: align columns and avoid trailing separators.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

A formatted multiplication table

Print the multiplication table for 1 through 5 as five rows. Each row should contain five right-aligned products, separated by a single space. Use nested loops or a generator expression.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
for row in range(1, 6):    print(" ".join(f"{row * column:>3}" for column in range(1, 6)))

The outer loop selects the row, the inner expression selects the column, and the format specification keeps the columns aligned. The first row begins with a padded 1.

02

A star pyramid

For n = 4, print a centered pyramid: one star on the first row, three on the second, five on the third, and seven on the fourth. Use spaces for the left padding.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
n = 4for row in range(1, n + 1):    spaces = " " * (n - row)    stars = "*" * (2 * row - 1)    print(spaces + stars)

Each row removes one leading space and adds two stars. The relationship 2 * row - 1 produces the odd star counts that make the sides symmetrical.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01How many times does the inner loop run in total when both loops use range(3)?
02What does pass do inside a loop body?
03Why initialize a product accumulator to 1 rather than 0?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

A formatted multiplication table

Print the multiplication table for 1 through 5 as five rows. Each row should contain five right-aligned products, separated by a single space. Use nested loops or a generator expression.

EXPECTED OUTPUT
True 6))
True 6))
True 6))
True 6))
True 6))
main.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.