Border Number Square Pattern in Python

Beginner
⏱️ 7 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
Border Filling

What You’ll Learn

How to print a border number square in Python. Only the outer boundary contains numbers; the inside stays blank.

This is a great exercise for practicing 2D grids, indexing, and formatting output neatly.

⭐ Pattern Output

For n = 5, the pattern looks like this:

Output
1  2  3  4  5
16          6
15          7
14          8
13 12 11 10 9
1

Complete Python Program

Fill the border in four passes (top, right, bottom, left), then print the grid with fixed-width formatting.

Python
n = 5
grid = [["" for _ in range(n)] for _ in range(n)]

val = 1

# top row
for j in range(n):
    grid[0][j] = val
    val += 1

# right column
for i in range(1, n):
    grid[i][n - 1] = val
    val += 1

# bottom row (right to left)
for j in range(n - 2, -1, -1):
    grid[n - 1][j] = val
    val += 1

# left column (bottom to top)
for i in range(n - 2, 0, -1):
    grid[i][0] = val
    val += 1

for i in range(n):
    for j in range(n):
        if grid[i][j] == "":
            print(f"{'':>3}", end="")
        else:
            print(f"{grid[i][j]:>3}", end="")
    print()

🧠 How It Works

1

Create an empty grid

We build an n × n grid and leave the inside blank.

Setup
2

Fill the top and right borders

First we fill the top row left-to-right, then the right column top-to-bottom using a running counter val.

Top/Right
3

Fill the bottom and left borders

Next we fill the bottom row right-to-left, and finally fill the left column bottom-to-top.

Bottom/Left
4

Print with fixed-width formatting

We print each cell with width 3 so columns stay aligned even with multi-digit numbers.

Formatting
=

Border-only fill

Only the boundary gets numbers; the interior stays blank.

2

Variation — User Input Version

Read n from the user and generate the border-filled square.

Python
n = int(input("Enter n: "))
if n < 1:
    raise ValueError("n must be at least 1")

grid = [["" for _ in range(n)] for _ in range(n)]
val = 1

for j in range(n):
    grid[0][j] = val
    val += 1

for i in range(1, n):
    grid[i][n - 1] = val
    val += 1

for j in range(n - 2, -1, -1):
    grid[n - 1][j] = val
    val += 1

for i in range(n - 2, 0, -1):
    grid[i][0] = val
    val += 1

for row in grid:
    for cell in row:
        print(f"{cell:>3}" if cell != "" else f"{'':>3}", end="")
    print()

💡 Tips for Enhancement

Try These

  • Fill multiple layers (spiral) instead of only the outer border
  • Use a different start value instead of 1
  • Replace numbers with letters to create an alphabet border
  • Store the grid and reuse it for other pattern operations
  • Print separators (like |) between columns for debugging

Avoid

  • Printing without fixed width (multi-digit numbers break alignment)
  • Forgetting to skip the corners when filling multiple sides (duplicates)
  • Using n < 1 without validation
  • Mixing strings and ints without consistent formatting

Key Takeaways

1

Fill the border in four passes: top, right, bottom, left.

2

Keep a running counter to place consecutive numbers.

3

Use fixed-width printing to keep columns aligned.

4

Printing an \(n \times n\) grid costs O(n²).

❓ Frequently Asked Questions

We fill the bottom row from right to left so that the numbers continue consecutively around the border.
By starting the right column from row 2, the bottom row from column n-1, and the left column from row n-1, corners are filled exactly once.
Yes. You can extend this into a spiral fill by repeating the same four-pass border logic for inner layers.
O(n²), because output itself is \(n \times n\).

Explore More Python Number Patterns!

Border patterns are a stepping stone to spiral and matrix traversal problems.

All Number Patterns →
Did you know?

The same border-filling idea is used to solve spiral matrix problems—just repeat the border fill for inner layers.

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.

7 people found this page helpful