Square Numbers Pyramid in Python

Beginner
⏱️ 9 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops + Math

What You’ll Learn

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.

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.

Outer Loop

r = 1..rows

for r in range(1, rows + 1): — each row prints 2*r - 1 perfect squares.

Leading Spaces

Center rows

print(" " * (4 * (rows - r)), end="") indents narrow rows so the pyramid stays centered.

Counter m

Running sequence

Increment m, then print f"{m*m:4d}" — squares progress 1, 4, 9, 16, 25, … continuously.

Live Preview

2–5 levels

Pick a level count and draw the square-number pyramid in the browser.

O(n²)

Complexity

Total square prints = for n rows; extra memory stays O(1).

Introduction

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.

Why it matters?

It combines nested loops with math and formatted output — a key step after Program 40’s alternating rows.

Key Highlights

Odd row widths

Each row prints 2r - 1 squares.

Centering

Leading spaces shift narrow rows right.

vs Program 40

Program 40 alternates 1/0; Program 41 prints perfect squares.

Series Foundation

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().

📝 Problem & Approach

Given a row count rows (e.g. 5), print a centered pyramid of perfect squares using a running counter m and fixed-width columns.

Python
# rows = 5 (conceptual shape)
#                   1
#               4   9  16
#          25  36  49  64  81
# ...

Inputs & Outputs

ItemTypeDescription
rowsintNumber of pyramid rows — outer loop runs r = 1..rows.
rintOuter loop — row index; inner loop prints 2*r - 1 squares.
mintRunning counter — each printed value is m*m.

Minimal workflow

Pseudocode
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 comparison

ApproachIdeaBest for
Nested loops + counter1, 4 9 16, …Learning and interviews
User-input rowsint(input(...))Flexible console programs
Left-aligned variantSkip leading spacesEasier tracing on paper

⚡ Quick Reference

GoalPattern
Walk rowsfor r in range(1, rows + 1):
Center rowprint(" " * (4 * (rows - r)), end="")
Print squaresm += 1; print(f"{m*m:4d}", end="")
Squares per rowfor _ in range(2 * r - 1):
End the rowprint()
Wider columnsf"{m*m:6d}" when squares exceed 999
Program 40 contrastAlternating 1/0 with shrinking rows — not perfect squares

📋 Fixed Rows vs User Input vs Left-Aligned

Same square-number pyramid — different ways to control rows and alignment.

Outer loop
r = 1..rows

Each row prints 2r-1 squares

Counter
m += 1; m*m

Continuous perfect squares

Centering
4 * (rows - r)

Leading spaces per row

Learning tip
:4d width

Keeps columns aligned

Context

When This Pattern Shows Up

Reach for this pattern when teaching formatted output, centering, and running counters with nested loops.

  1. After Program 40

    Natural follow-up — perfect squares in a centered pyramid instead of alternating binary digits.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with input() for a flexible row count.

  4. Gateway to variants

    Print cubes with m**3 or skip centering for a left-aligned pyramid — see Example 3.

  5. Not a UI layout tool

    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.

🔮 Live Preview

Choose a level count between 2 and 5 and draw the square-number pyramid in the browser.

Try 2, 3, or 4. Max up to 5 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed rows, user input, and a left-aligned variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the square-number pyramid with nested loops and formatted output.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

Python
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()

How It Works

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.

📈 User Input

Read the row count with input() instead of hard-coding 5.

Example 2 — User Input

Read rows with input() and int() (wrap in try/except ValueError in real apps).

Python
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()

How It Works

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.

⚡ Left-Aligned

Skip the leading-space print to draw squares flush left — easier to trace on paper.

Example 3 — Left-Aligned Pyramid

Same squares and counter — no leading spaces.

Python
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()

How It Works

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.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed. Set rows = 5, m = 0, and loop variable r.

Setup
2

Outer loop walks rows

for r in range(1, rows + 1): — each row prints 2*r - 1 perfect squares.

Row
3

Leading spaces

print(" " * (4 * (rows - r)), end="") — indents narrow rows so the pyramid stays centered.

Center
4

Print squares

m += 1; print(f"{m*m:4d}", end="") — fixed-width perfect squares in sequence.

Squares
5

New line

print() ends the row after the inner loop finishes.

Break
=

Square-number pyramid complete

Total prints for 5 rows = 1+3+5+7+9 = 25O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of r, indent count, square count, m range, and row output.

rSpacesSquaresm rangeValues
116111
21232–44 9 16
3855–925 36 49 64 81
44710–16100 121 144 … 256
50917–25289 324 … 625

Squares per row = 2*r - 1 — total prints = 1+3+5+7+9 = 25 = 5² for 5 rows.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change :4d to :6d when squares exceed 999.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: continue to Program 42 for a hollow square of 1s.

3. Console Formatting Drills

Practice print vs row newline without complex math.

Example: put print() inside the inner loop by mistake.

4. Spaced Output

Add spaces between digits once the two-loop structure works.

Example: use f"{m*m:6d}" for larger pyramids.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed squares for 5 rows — total is 25 ().

6. Input Validation Labs

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.

Advantages

Why this pattern earns a permanent spot in beginner Python courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    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.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Use Fixed-Width Formatting

    f"{m*m:4d}" keeps columns aligned — widen to :6d when squares exceed 999.

  2. 2. Call try/except ValueError

    Use try/except ValueError so bad input does not crash when converting rows.

  3. 3. Keep print() Outside the Inner Loop

    Only call print() after the inner loop finishes the row.

  4. 4. Separate Spacing from Values

    Print leading spaces before the inner loop — keep the square-print logic inside the inner loop only.

  5. 5. Dry-Run rows = 3

    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.

Common Pitfalls

Mistakes that commonly break square-number pyramids.

  1. 1. Newline Inside the Inner Loop

    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.

  2. 2. Forgetting Fixed Width

    Printing bare m*m without :4d makes columns drift as numbers get wider.

    → Always use f"{m*m:4d}" (or wider) for aligned columns.

  3. 3. Resetting m Each Row

    m = 0 inside the outer loop restarts squares on every row instead of continuing the sequence.

    → Initialize m = 0 once before the outer loop.

  4. 4. Forgetting the Row Break

    Omitting print() glues every digit onto one endless line.

    → Always end the row after the inner loop.

  5. 5. Bare int(input())

    Letters or empty input raise ValueError with bare int(input()).

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single square row

Output is just 1 on one centered line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

Treat as invalid; re-prompt instead of silent empty output.

rows = 2

Smallest pyramid

Two rows: 1 then 4 9 16.

Bad input

Non-numeric input

Bare int(input()) raises ValueError on bad input — use try/except first.

Large rows

Large row count

Each row prints 2*r - 1 squares — total work grows as .

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Alternating 1/0 triangle

  • Review Program 40
  • Alternating 1/0 with shrinking rows

2. Hollow square of 1s

  • Continue with Program 42
  • Boundary check with nested loops

3. Cube pyramid

  • Replace m*m with m**3
  • Same loops, different math

4. Left-aligned variant

  • Remove leading-space print
  • Same counter, no centering

Notes

  • Square rule. Outer loop: r = 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.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Total squares for n rows = — 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().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

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 — keep f"{m*m:4d}" for aligned columns and print() for the row break.

💡 Best Practices

✅ Do

  • Use for r in range(1, rows + 1): in the outer loop
  • Inner: for _ in range(2 * r - 1): prints odd counts per row
  • Use f"{m*m:4d}" for aligned columns and print() after each row
  • Center with print(" " * (4 * (rows - r)), end="") before the inner loop
  • Wrap int(input()) in try/except ValueError

❌ Don’t

  • Call print() inside the inner square loop
  • Reset m inside the outer loop (breaks the sequence)
  • Skip fixed-width formatting (columns drift)
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this square-number pyramid

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

range(1, rows + 1)

Code
03

Inner loop

range(2*r - 1)

Code
04

Centering

4 * (rows - r) spaces

Align
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

A centered pyramid of perfect squares: row 1 prints 1 (1²), row 2 prints 4 9 16 (2², 3², 4²), and so on.
The inner loop runs range(2 * r - 1) times per row r — that produces odd counts: 1, 3, 5, 7, 9 squares.
Leading spaces via print(" " * (4 * (rows - r)), end="") shift narrow rows right so the pyramid stays centered.
m starts at 0 and increments before each print. Each value printed is m*m — the next perfect square in sequence.
Fixed-width columns keep the pyramid aligned as squares grow from 1 to 625. Without it, columns drift apart.
Increase rows — see Example 2 for reading levels with input().
Program 40 alternates 1 and 0 with shrinking rows. Program 41 prints perfect squares in a centered pyramid with growing odd-width rows.
O(n²) for n rows — total prints are 1+3+5+...+(2n-1) = n².
Yes — remove the leading-space print to get a left-aligned pyramid. See Example 3.

Did you Know? 🔊

Each printed value is from a running counter m. Row widths are odd (1, 3, 5, 7, 9) — total prints for n rows = .

Continue to Program 42

Move on to the hollow square of 1s in the Python number-pattern series.

Program 42 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful