π Python Pattern Challenge — Day 10
Pattern printing is a great way to strengthen your Python logic, nested loops, conditions, and problem-solving skills. For Day 10, we’re taking the challenge a step further with a square spiral pattern.
Unlike a normal square or diamond, this pattern requires you to think about rows, columns, boundaries, and changing positions.
Solution 1 — Using Nested Loops
n = 7 for i in range(n): for j in range(n): if ( i == 0 or i == n - 1 or j == 0 or j == n - 1 or (2 <= i <= 4 and 2 <= j <= 4) and (i == 2 or i == 4 or j == 2 or j == 4) ): print("*", end=" ") else: print(" ", end=" ") print()
How it works:
The pattern is created by checking the position of every row and column.
- i == 0 → top border
- i == n - 1 → bottom border
- j == 0 → left border
- j == n - 1 → right border
- The additional conditions create the inner square.
This approach helps you understand how multiple conditions can be combined to create complex patterns.
Solution 2 — Using a Pattern List
pattern = [ "*********", "* *", "* ***** *", "* * * *", "* ***** *", "* *", "*********" ] for row in pattern: print(" ".join(row))
How it works:
Instead of calculating every position, we store each row as a string.
For example:
********* * * * ***** *
Then:
for row in pattern:
prints each row one by one.
This approach is simple and useful when the pattern is fixed.
Solution 3 — Using a Function
def pattern(n): for i in range(n): for j in range(n): edge = i in (0, n - 1) or j in (0, n - 1) inner = 2 <= i <= n - 3 and 2 <= j <= n - 3 inner_edge = i in (2, n - 3) or j in (2, n - 3) print("*" if edge or (inner and inner_edge) else " ", end=" ") print() pattern(7)
How it works:
Here, we divide the logic into three parts:
edgecontrols the outer square.
innerdefines the inner region.
inner_edgecreates the inner boundary.
This makes the code more structured and reusable.
⚡ Short & Clean Code
p = ["*********", "* *", "* ***** *", "* * * *", "* ***** *", "* *", "*********"] for x in p: print(" ".join(x))
π₯ Short, readable, and perfect for a fixed pattern challenge.
π Challenge Yourself
Can you modify this pattern:
- Create a larger spiral using n?
- Generate the pattern without manually writing the rows?
- Use only nested loops and conditions?
- Replace * with numbers?
- Create a spiral using one continuous path?
- Solve it in the shortest possible Python code?
Drop your solution below! π
10 Days. 10 Patterns. Stronger Python Logic. ππ₯
Learn • Practice • Grow with CLCODING

0 Comments:
Post a Comment