Hollow Square of 1s in Python

What You’ll Learn
How to print a hollow square pattern of 1s in Python. The key idea is to print 1 on the border (first/last row or first/last column) and print spaces in the inner cells.
This is a classic practice problem for combining nested loops with a simple boundary condition.
⭐ Pattern Output
For n = 5, the pattern looks like this:
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1Complete Python Program
We loop through a 5×5 grid. If the current cell is on the boundary, we print 1; otherwise we print a space.
n = 5
for i in range(1, n + 1):
for j in range(1, n + 1):
if i == 1 or i == n or j == 1 or j == n:
print("1", end=" ")
else:
print(" ", end=" ")
print()🧠 How It Works
Set the grid size
n = 5 makes a 5×5 square.
Two loops for rows and columns
The outer loop chooses the row (i) and the inner loop chooses the column (j).
Boundary check
i == 1, i == n, j == 1, or j == n means the cell is on the border, so we print 1.
Print spaces inside
If the cell is not on the border, we print a space so the square becomes hollow.
Hollow square frame
We visit every cell in an n×n grid, so runtime is O(n²).
Variation — User Input Version
This version lets the user choose the size n at runtime. It also validates that n is at least 2 (a 1×1 frame isn’t very interesting).
n = int(input("Enter the size (n >= 2): "))
if n < 2:
raise ValueError("n must be at least 2")
for i in range(1, n + 1):
for j in range(1, n + 1):
if i == 1 or i == n or j == 1 or j == n:
print("1", end=" ")
else:
print(" ", end=" ")
print()💡 Tips for Enhancement
Try These
- Print a different border character (like
0,#, or*) - Use
range(n)(0-based) and checki == 0/i == n-1 - Print a hollow rectangle by using different
rowsandcols - Fill the inside with a different digit to create a framed pattern
- Add spacing control (e.g., two spaces after each
1) for wider output
Avoid
- Forgetting the
end=" "which keeps values on the same line - Mixing row and column checks (keep the boundary condition clear)
- Using
n < 2without handling it (output will be confusing) - Printing tabs inconsistently (spaces are more predictable across consoles)
Key Takeaways
Use nested loops to iterate through an n×n grid.
Print 1 when you are on the border: first/last row or first/last column.
Print spaces for inner cells to make the square hollow.
Total checks are n², so runtime is O(n²).
❓ Frequently Asked Questions
i is 1 or n (top/bottom row) or j is 1 or n (left/right column).rows and cols, and check boundaries with those limits.Explore More Python Number Patterns!
Keep practicing loops by trying diamonds, pyramids, and framed patterns.
A hollow n×n frame contains 4n-4 border cells (for n ≥ 2). Everything else is inside the frame.
8 people found this page helpful
