Shape Rule
m² per value
Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.

The square number pyramid prints 1, then 4 9 16, then 25 36 49 64 81, … — a natural step after Program 40’s alternating 1/0 pattern. This tutorial covers odd-length rows, indentation centering, a running counter m, f-string formatting, a live preview, worked Python examples, edge cases, and complexity.
m² per value
Row 1 prints 1, row 2 prints 4 9 16, row 3 prints five squares — each value is the next perfect square.
r = 1..rows
for r in range(1, rows + 1): — each row prints 2*r - 1 perfect squares.
Center rows
print(" " * (4 * (rows - r)), end="") indents narrow rows so the pyramid stays centered.
Running sequence
Increment m, then print f"{m*m:4d}" — squares progress 1, 4, 9, 16, 25, … continuously.
2–5 levels
Pick a level count and draw the square-number pyramid in the browser.
Complexity
Total square prints = n² for n rows; extra memory stays O(1).
A square number pyramid prints perfect squares in centered rows of odd length — 1, then 3, then 5 squares per row. With rows = 5, the output starts with 1, then 4 9 16, then 25 36 49 64 81, and continues.
In Python the outer loop runs r = 1..rows, leading spaces center each row, and the inner loop prints f"{m*m:4d}" while incrementing m.
It combines nested loops with math and formatted output — a key step after Program 40’s alternating rows.
Each row prints 2r - 1 squares.
Leading spaces shift narrow rows right.
Program 40 alternates 1/0; Program 41 prints perfect squares.
Follow Program 40; continue to Program 42 (hollow square) next.
In short: outer r = 1..rows, indent spaces, inner print f"{m*m:4d}", increment m, then print().
Given a row count rows (e.g. 5), print a centered pyramid of perfect squares using a running counter m and fixed-width columns.
# rows = 5 (conceptual shape)
# 1
# 4 9 16
# 25 36 49 64 81
# ... | Item | Type | Description |
|---|---|---|
rows | int | Number of pyramid rows — outer loop runs r = 1..rows. |
r | int | Outer loop — row index; inner loop prints 2*r - 1 squares. |
m | int | Running counter — each printed value is m*m. |
m = 0
for r from 1 to rows:
print leading spaces
for _ from 1 to (2*r - 1):
m++
print m*m with fixed width
print newline | Approach | Idea | Best for |
|---|---|---|
| Nested loops + counter | 1, 4 9 16, … | Learning and interviews |
| User-input rows | int(input(...)) | Flexible console programs |
| Left-aligned variant | Skip leading spaces | Easier tracing on paper |
| Goal | Pattern |
|---|---|
| Walk rows | for r in range(1, rows + 1): |
| Center row | print(" " * (4 * (rows - r)), end="") |
| Print squares | m += 1; print(f"{m*m:4d}", end="") |
| Squares per row | for _ in range(2 * r - 1): |
| End the row | print() |
| Wider columns | f"{m*m:6d}" when squares exceed 999 |
| Program 40 contrast | Alternating 1/0 with shrinking rows — not perfect squares |
Same square-number pyramid — different ways to control rows and alignment.
r = 1..rowsEach row prints 2r-1 squares
m += 1; m*mContinuous perfect squares
4 * (rows - r)Leading spaces per row
:4d widthKeeps columns aligned
Reach for this pattern when teaching formatted output, centering, and running counters with nested loops.
Natural follow-up — perfect squares in a centered pyramid instead of alternating binary digits.
Outer/inner bound practice with an immediate visual check.
Combine loops with input() for a flexible row count.
Print cubes with m**3 or skip centering for a left-aligned pyramid — see Example 3.
This is a console teaching pattern — not how you build modern app screens.
Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.
Choose a level count between 2 and 5 and draw the square-number pyramid in the browser.
Three complete Python programs — fixed rows, user input, and a left-aligned variant. Click View Output to reveal sample console results.
Print five rows of the square-number pyramid with nested loops and formatted output.
rows = 5Hard-coded row count — ideal for first demos and screenshots.
rows = 5
m = 0
for r in range(1, rows + 1):
print(" " * (4 * (rows - r)), end="")
for _ in range(2 * r - 1):
m += 1
print(f"{m*m:4d}", end="")
print() When r = 1, one square prints — 1. When r = 2, three squares print — 4 9 16 (from m = 2, 3, 4). Leading spaces shift narrow rows right so the pyramid stays centered.
Read the row count with input() instead of hard-coding 5.
Read rows with input() and int() (wrap in try/except ValueError in real apps).
rows = int(input("Enter number of rows: "))
m = 0
for r in range(1, rows + 1):
print(" " * (4 * (rows - r)), end="")
for _ in range(2 * r - 1):
m += 1
print(f"{m*m:4d}", end="")
print() Same square-filling core as Example 1; only the source of rows changes from a literal to user input. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.
Skip the leading-space print to draw squares flush left — easier to trace on paper.
Same squares and counter — no leading spaces.
rows = 5
m = 0
for r in range(1, rows + 1):
for _ in range(2 * r - 1):
m += 1
print(f"{m*m:4d}", end="")
print() Only the leading-space print is removed — m*m and :4d formatting stay the same as Example 1. Rows grow wider to the right without centering.
No imports needed. Set rows = 5, m = 0, and loop variable r.
for r in range(1, rows + 1): — each row prints 2*r - 1 perfect squares.
print(" " * (4 * (rows - r)), end="") — indents narrow rows so the pyramid stays centered.
m += 1; print(f"{m*m:4d}", end="") — fixed-width perfect squares in sequence.
print() ends the row after the inner loop finishes.
Total prints for 5 rows = 1+3+5+7+9 = 25 — O(n²) time, O(1) extra memory.
rows = 5Trace each outer-loop value of r, indent count, square count, m range, and row output.
r | Spaces | Squares | m range | Values |
|---|---|---|---|---|
1 | 16 | 1 | 1 | 1 |
2 | 12 | 3 | 2–4 | 4 9 16 |
3 | 8 | 5 | 5–9 | 25 36 49 64 81 |
4 | 4 | 7 | 10–16 | 100 121 144 … 256 |
5 | 0 | 9 | 17–25 | 289 324 … 625 |
Squares per row = 2*r - 1 — total prints = 1+3+5+7+9 = 25 = 5² for 5 rows.
Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.
Clearest visual proof that outer and inner bounds interact.
Example: change :4d to :6d when squares exceed 999.
Foundation for inverted, pyramid, diamond, and hollow variants.
Example: continue to Program 42 for a hollow square of 1s.
Practice print vs row newline without complex math.
Example: put print() inside the inner loop by mistake.
Add spaces between digits once the two-loop structure works.
Example: use f"{m*m:6d}" for larger pyramids.
Triangular totals make O(n²) concrete for beginners.
Example: count printed squares for 5 rows — total is 25 (5²).
Pair the pattern with input() return checks and positive-row checks.
Example: reject rows <= 0 and re-prompt.
Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.
Why this pattern earns a permanent spot in beginner Python courses.
Wrong bounds show up immediately as a broken staircase.
Only loops and console output — no arrays or math libraries.
Invert, center, hollow, or change the fill character with small edits.
Streaming output needs no storage beyond loop counters.
Pro Tip: trace r, m, and indent count on paper for rows = 3 before coding the full demo.
Small habits that keep number-pattern code clean.
f"{m*m:4d}" keeps columns aligned — widen to :6d when squares exceed 999.
try/except ValueErrorUse try/except ValueError so bad input does not crash when converting rows.
Only call print() after the inner loop finishes the row.
Print leading spaces before the inner loop — keep the square-print logic inside the inner loop only.
Trace r = 1, 2, 3 and watch m grow before coding the full rows = 5 demo.
Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put print() inside the inner loop.
Mistakes that commonly break square-number pyramids.
Each square lands on its own line — you get a column, not a pyramid.
→ Use print(f"{m*m:4d}", end="") for squares; print() only after the inner loop.
Printing bare m*m without :4d makes columns drift as numbers get wider.
→ Always use f"{m*m:4d}" (or wider) for aligned columns.
m = 0 inside the outer loop restarts squares on every row instead of continuing the sequence.
→ Initialize m = 0 once before the outer loop.
Omitting print() glues every digit onto one endless line.
→ Always end the row after the inner loop.
int(input())Letters or empty input raise ValueError with bare int(input()).
→ Catch ValueError and re-prompt on failure.
Check these inputs before calling the solution done.
Output is just 1 on one centered line.
Outer loop never runs — print nothing or show a message.
rows < 0Treat as invalid; re-prompt instead of silent empty output.
Two rows: 1 then 4 9 16.
Bare int(input()) raises ValueError on bad input — use try/except first.
Each row prints 2*r - 1 squares — total work grows as n².
Try these variations to lock in the pattern.
m*m with m**3r = 1..rows. Inner loop: range(2*r - 1). Value: m*m with :4d width.print(" " * (4 * (rows - r)), end="") centers rows; print() advances to the next line.rows > 0 for interactive programs; rows = 1 should print a single 1.n rows = n² — the sum of the first n odd numbers.Quick Takeaway: outer loop r = 1..rows, indent spaces, inner range(2*r - 1) with f"{m*m:4d}", then print().
| Program | Time | Extra space |
|---|---|---|
| Nested loops (Examples 1–3) | O(n²) | O(1) |
| Smaller demo (Example 3) | O(n²) | O(1) |
The square number pyramid is a compact nested-loop lesson: a running counter m prints perfect squares while leading spaces keep rows centered. Master the fixed-rows version, then try user input and the left-aligned variant.
Practice the three examples above, then continue to Program 42 for the hollow square of 1s.
Each value is m² — keep f"{m*m:4d}" for aligned columns and print() for the row break.
for r in range(1, rows + 1): in the outer loopfor _ in range(2 * r - 1): prints odd counts per rowf"{m*m:4d}" for aligned columns and print() after each rowprint(" " * (4 * (rows - r)), end="") before the inner loopint(input()) in try/except ValueErrorprint() inside the inner square loopm inside the outer loop (breaks the sequence)rows = 1 edge casePrint the pattern the beginner-friendly way.
Each value is m²
Definitionrange(1, rows + 1)
Coderange(2*r - 1)
Code4 * (rows - r) spaces
AlignO(n²) time
AnalysisEach printed value is m² from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total prints for n rows = n².
Move on to the hollow square of 1s in the Python number-pattern series.
12 people found this page helpful