๐ Python Pattern Challenge — Day 25
Pattern printing is a fun way to improve your Python loops, number sequences, and logical thinking. For Day 25, let's create a beautiful Number Pyramid Pattern ๐บ.
This pattern starts with 1 at the top and expands row by row. Each row increases up to a middle number and then decreases symmetrically, creating a pyramid-like design.
๐ฏ Today's Challenge
Write a Python program to print the following pattern:
Best and cleanest code will be rewarded! ๐
Solution 1 — Using Nested for Loops
n = 5 for i in range(1, n + 1): print(" " * (n - i), end="") for j in range(1, i + 1): print(j, end=" ") for j in range(i - 1, 0, -1): print(j, end=" ") print()
How It Works
1. Controlling the rows
for i in range(1, n + 1):This loop creates five rows, increasing the value of i from 1 to 5.
2. Adding spaces
print(" " * (n - i), end="")Spaces move each row toward the center, forming the pyramid shape.
3. Printing increasing numbers
for j in range(1, i + 1):This loop prints numbers from 1 up to the current row number.
4. Printing decreasing numbers
for j in range(i - 1, 0, -1):This loop prints the numbers in reverse order, without repeating the middle number.
For example, when i = 4, the row becomes:
1 2 3 4 3 2 1Solution 2 — Using a Simple List
for i in range(1, 6): row = list(range(1, i + 1)) row += list(range(i - 1, 0, -1)) print(" " * (5 - i) + " ".join(map(str, row)))
Here, range() creates the increasing and decreasing sequences, while map(str, row) converts the numbers into strings for joining.
Solution 3 — Using a Function
def number_pyramid(n): for i in range(1, n + 1): left = list(range(1, i + 1)) right = list(range(i - 1, 0, -1)) row = left + right print(" " * (n - i) + " ".join(map(str, row))) number_pyramid(5)
You can change number_pyramid(5) to number_pyramid(7) to create a larger pyramid.
⚡ Short & Clean Code
for i in range(1, 6): print(" " * (5-i), *range(1, i+1), *range(i-1, 0, -1))
This compact version generates the same number pyramid using Python's unpacking operator.
๐ Challenge Yourself
Can you modify this pattern?
Increase the pyramid to 10 rows.
Create the same pattern using a while loop.
Replace numbers with alphabets.
Print the pyramid upside down.
Create a similar pattern using * symbols.
Drop your solution below! ๐
25 Days. 25 Patterns. Stronger Python Logic. ๐๐ฅ
Learn • Practice • Grow with CLCODING ๐
.png)


0 Comments:
Post a Comment