π Python Pattern Challenge — Day 4
Pattern printing is one of the best ways to improve your Python logic, loops, string handling, and problem-solving skills.
For Day 4, let's take the challenge one step further and create a diamond-shaped star pattern. The real challenge is controlling both spaces and stars as the pattern grows and then shrinks.
Today's Challenge
Write a Python program to print:
Best and cleanest code will be rewarded! π
Solution 1 — Using Two for Loops
n = 5 for i in range(1, n + 1): print(" " * (n - i) + "* " * (2 * i - 1)) for i in range(n - 1, 0, -1): print(" " * (n - i) + "* " * (2 * i - 1))
How it works:
- " " * (n - i) → creates the indentation before the stars.
- "* " * (2 * i - 1) → creates an increasing number of stars.
- The first loop creates the upper half.
- The second loop creates the lower half.
- 2 * i - 1 generates odd numbers: 1, 3, 5, 7, 9.
Solution 2 — Using Nested Loops
n = 5 for i in range(1, n + 1): for j in range(n - i): print(" ", end=" ") for j in range(2 * i - 1): print("*", end=" ") print() for i in range(n - 1, 0, -1): for j in range(n - i): print(" ", end=" ") for j in range(2 * i - 1): print("*", end=" ") print()
How it works:
Here, nested loops separately control:
- Spaces → position of the stars.
- Stars → number of stars in each row.
- The first outer loop builds the diamond upward.
- The second outer loop builds it downward.
This approach is especially useful for beginners because you can clearly see how rows, spaces, and stars are controlled independently.
Solution 3 — Using String Multiplication
n = 5 for i in list(range(1, n + 1)) + list(range(n - 1, 0, -1)): print(" " * (n - i) + "* " * (2 * i - 1))
How it works:
Instead of writing two separate loops, we create the complete sequence of rows:
1, 2, 3, 4, 5, 4, 3, 2, 1Then:
" " * (n - i)controls the indentation, while:
"* " * (2 * i - 1)controls the stars.
This makes the solution short, clean, and reusable.
π Challenge Yourself
Can you create the same diamond pattern:
- Using a while loop?
- Using only one loop?
- Without using nested loops?
- By taking the size n as user input?
- In the shortest possible Python code?
Drop your solution below! π
Learn • Practice • Grow with CLCODING ππ»

0 Comments:
Post a Comment