Loop drills and patterns
Build fluency with nested loops, accumulators, prime tests, and formatted output by writing the classic loop exercises properly.
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.
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.
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.
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.
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.
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.
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.
Explore a worked solution
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.
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.
Explore a worked solution
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.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
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.
True 6)) True 6)) True 6)) True 6)) True 6))
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.