π Python Pattern Challenge — Day 5
Pattern printing is a great way to strengthen your Python logic, loops, conditions, and problem-solving skills. Today’s challenge is a little different — instead of printing a completely filled pyramid, we’ll create a hollow pyramid using stars.
Today's Challenge
Write a Python program to print:
Best and cleanest code will be rewarded! π
Solution 1 — Using a for Loop
n = 5 for i in range(n): spaces = " " * (n - i - 1) if i == 0: print(spaces + "*") elif i == n - 1: print("* " * (2 * n - 1)) else: print(spaces + "* " + " " * (2 * i - 1) + "*")
How it works:
- " " * (n - i - 1) → creates the spaces before the stars.
- The first row contains only one star.
- The middle rows contain stars only at the two boundaries.
- The last row contains all stars.
- 2 * i - 1 controls the empty space inside the pyramid.
Solution 2 — Using Nested Loops
n = 5 for i in range(n): spaces = " " * (n - i - 1) if i == 0: print(spaces + "*") elif i == n - 1: print("* " * (2 * n - 1)) else: print(spaces + "* " + " " * (2 * i - 1) + "*")
How it works:
Here, the nested loops control the pattern step by step:
- First loop → creates the left indentation.
- Second loop → controls the pyramid width.
- j == 0 → prints the left boundary star.
- j == 2 * i → prints the right boundary star.
- i == n - 1 → fills the entire bottom row.
This approach is useful for understanding how conditions can control individual characters inside a pattern.
Solution 3 — Using a Single for Loop
n = 5 for i in range(n): if i == 0: print(" " * (n - 1) * 2 + "*") elif i == n - 1: print("* " * (2 * n - 1)) else: print(" " * (n - i - 1) + "* " + " " * (2 * i - 1) + "*")
Here, each row is constructed dynamically using string multiplication and concatenation, without nested loops.
π Challenge Yourself
Can you create the same pattern:
- Using a while loop?
- Without using nested loops?
- By taking the number of rows using user input?
- Make it a hollow diamond instead of a pyramid?
- In the shortest possible Python code?
Drop your solution below! π
Learn • Practice • Grow with CLCODING ππ»

0 Comments:
Post a Comment