π Python Pattern Challenge — Day 8
Pattern printing is a great way to strengthen your Python logic, loops, conditions, and problem-solving skills. Today’s challenge focuses on creating a hollow square pattern using stars.
The interesting part is that we don't print stars everywhere. Instead, we use conditions to print stars only on the boundary and leave the inside empty.
Today's Challenge
Write a Python program to print:
Best and cleanest code will be rewarded! π
Solution 1 — Using Nested Loops
n = 5 for i in range(n): for j in range(n): if i == 0 or i == n - 1 or j == 0 or j == n - 1: print("*", end=" ") else: print(" ", end=" ") print()
How it works:
The main logic is this condition:
i == 0 or i == n - 1 or j == 0 or j == n - 1It checks whether the current position lies on the boundary.
- i == 0 → top border
- i == n - 1 → bottom border
- j == 0 → left border
- j == n - 1 → right border
If any condition is true, Python prints *. Otherwise, it prints a space.
Solution 2 — Using a Single for Loop
n = 5 for i in range(n): if i == 0 or i == n - 1: print("* " * n) else: print("* " + " " * (n - 2) + "*")
How it works:
We divide the rows into two types.
Top & Bottom Rows
"* " * nThese rows are completely filled with stars.
Middle Rows
"* " + " " * (n - 2) + "*"Only the first and last positions contain stars.
This makes the code short, clean, and beginner-friendly.
Solution 3 — Using a while Loop
n = 5 i = 0 while i < n: j = 0 while j < n: if i in (0, n - 1) or j in (0, n - 1): print("*", end=" ") else: print(" ", end=" ") j += 1 print() i += 1
Here, both rows and columns are controlled using while loops.
The if condition determines whether each position should contain a star or remain empty.
⚡ Short & Clean Code
n = 5 for i in range(n): print("* " * n if i in (0, n - 1) else "* " + " " * (n - 2) + "*")
π₯ A single loop with a conditional expression creates the complete hollow square.
π Challenge Yourself
Can you modify this pattern:
- Create a hollow rectangle?
- Take the size using input()?
- Create a hollow triangle?
- Replace * with numbers?
- Create a hollow diamond?
- Solve it using the shortest possible Python code?
Drop your solution below! π
Learn • Practice • Grow with CLCODING ππ»

0 Comments:
Post a Comment