Python Square Number Pyramid Pattern

Beginner
5 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A square-numbers pyramid prints consecutive perfect squares in centered rows whose widths are odd: 1, then 3, then 5, and so on.

Remember
Rule: odd row widths; print next m² with width 4

                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625   ← 5 levels

Follows the alternating 1/0 pattern in Program 40; next is the hollow square border of 1s in Program 42.

How to Solve It

One odd-step outer loop with indent, then a continuous square counter — pads with " ", values with f"{m*m:4d}".

MethodIdeaBest for
Centered pyramidIndent, then print m*m with :4dLearning, interviews, exams
Levels inputSame logic with max_width = 2*levels - 1Practice / demos

Pseudocode

Pseudocode
maxWidth = 2 * levels - 1
m = 1
for i from 1 to maxWidth step 2:
    for j from i to maxWidth-1:
        print two spaces
    repeat i times:
        print m*m (width 4), then m = m + 1
    print newline

Cheat sheet

GoalPattern
Odd row widthsfor i in range(1, max_width + 1, 2):
Center the rowfor j in range(i, max_width): print(" ", end="")
Next squareprint(f"{m * m:4d}", end=""); m += 1
End the rowprint()

Printing Numbers vs Starting a New Line

APIEffectUse for
print(" ", end="") / print(f"{m*m:4d}", end="")Stays on the same lineEach indent or square
print()Ends the current lineAfter both inner loops

Print indents and squares without a newline, then end the row once.

Live Preview

Change the level count and the square pyramid updates instantly — capped at 5 for readable demos.

Whole numbers from 1 to 5 (keeps width-4 columns readable). Tap a chip or type a value — the preview redraws as you go.

Live result 5 levels · 25 squares
                   1
               4   9  16
          25  36  49  64  81
     100 121 144 169 196 225 256
 289 324 361 400 441 484 529 576 625

Worked Walkthrough — levels = 3

max_width = 5. Trace indents and the running square counter.

iIndent / squaresPrinted row
14 pads / 11
32 pads / 4 9 164 9 16
5none / 25..8125 36 49 64 81

Total squares for n levels = n². Counter m never resets between rows.

Python Programs

Three complete programs: fixed 5 levels, input() levels, and a compact 3-level demo. Use View Output to reveal sample results.

Example 1 — Fixed levels = 5

Odd-step outer loop; indent, then print continuous m*m with width-4 formatting.

Python
max_width = 9
m = 1

for i in range(1, max_width + 1, 2):
    for j in range(i, max_width):
        print("  ", end="")

    for k in range(1, i + 1):
        print(f"{m * m:4d}", end="")
        m += 1

    print()

How It Works

1. Odd widths. i takes 1, 3, 5, 7, 9 — that many squares print on each row.

2. Indent. Print " " while j runs from i to max_width - 1 so the tip stays centered.

3. Continuous m. Print m*m with f"{m*m:4d}", then increment m — never reset between rows.

Example 2 — User Input Levels

Read levels with input(), set max_width = 2 * levels - 1, then use the same pyramid logic.

Python
try:
    levels = int(input("Enter levels: "))
except ValueError:
    print("Please enter a positive whole number.")
    raise SystemExit(1)

if levels < 1:
    print("Please enter a positive whole number.")
    raise SystemExit(1)

max_width = 2 * levels - 1
m = 1

for i in range(1, max_width + 1, 2):
    for j in range(i, max_width):
        print("  ", end="")

    for k in range(1, i + 1):
        print(f"{m * m:4d}", end="")
        m += 1

    print()

How It Works

1. Prompt and validate. Catch ValueError; require levels >= 1 before printing.

2. Same core. Three levels end at 81 with nine squares total.

3. Safer input tip. Cap demos for readable width-4 columns:

Safer input tip
if levels < 1 or levels > 5:
    print("Enter a whole number from 1 to 5.")
    raise SystemExit(1)

Example 3 — Compact levels = 3

Same structure with only three levels — easy to confirm odd widths and continuous m.

Python
levels = 3
max_width = 2 * levels - 1
m = 1

for i in range(1, max_width + 1, 2):
    for j in range(i, max_width):
        print("  ", end="")

    for k in range(1, i + 1):
        print(f"{m * m:4d}", end="")
        m += 1

    print()

How It Works

1. Same rules. Odd i sets count; indent; print the next squares.

2. Quick check. The base row has five values ending at 81.

3. Scale up next. Once the small demo is clear, use Examples 1–2 for five levels or user input.

Edge Cases & Pitfalls

Check these before calling the solution done.

reset m

Reset m = 1 each row

That restarts squares every line. Keep m outside the outer loop.

step 1

Loop i by 1 instead of 2

You get even widths too and lose the classic pyramid shape. Keep range(..., 2).

no :4d

Print m*m without width

Columns drift once values hit three digits. Prefer f"{m * m:4d}".

pad mismatch

Indent with one space

Pads should match half the number width — use " " (2 spaces) with :4d.

levels = 1

Single square

Output is just the formatted 1 — one level, one square.

input()

Catch ValueError

Bare int(input()) crashes on non-numeric text — wrap it in try/except ValueError.

Time and Space Complexity

ProgramTimeExtra space
Fixed / input (Examples 1–2)O(n²)O(1)
Compact levels = 3 (Example 3)O(n²)O(1)

Total printed squares are 1 + 3 + 5 + … + (2n−1) = n², so work is quadratic in the level count.

Key Takeaways

  • Rule: odd row widths via step 2; each cell prints the next m*m.
  • Center: indent with " " before printing the squares on each row.
  • end="" vs print(): indents and squares stay on the line; bare print() advances after each row.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each odd width, indent then print the next perfect squares from a shared counter.

Frequently Asked Questions

A centered pyramid of perfect squares: for 5 levels you get 1 / 4 9 16 / 25..81 / … / 289..625 — consecutive m² values in odd-width rows.
The outer loop increases i by 2 each time (range(..., 2)), so i takes odd values — each becomes the count of squares printed on that row.
An indentation loop prints two spaces before each row. As i grows, fewer pads are printed, so wider rows shift left and stay centered.
m starts at 1 and increments after every printed square. 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.
Program 40 alternates 1 and 0 with shrinking rows. Program 41 prints perfect squares in a centered pyramid with growing odd-width rows.
Use try/except ValueError around int(input()) and require levels >= 1 — see Example 2.
O(n²) for n levels — total prints are 1+3+5+…+(2n-1) = n².

Did you know?

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

Next: Hollow Square Border of 1s

Print a square frame of 1s with empty space inside.

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