Learn Python Programming by Improving your Logic by Writing Programs for various Patterns in Python
Write a Program Code to Print the different Star Patterns- Pyramid, Right Triangle (Right Triangle is 90 Degrees), Left Triangle, Right Downward Triangle (Right Triangle is 90 Degrees), Left Downward Triangle, Double Hill, Reverse Pyramid, Butterfly Diamond, Sandglass, Left Pascal’s Triangle, Right Pascal’s Triangle (Right Triangle is 90 Degrees)
Pyramid
def print_pyramid(rows):
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
# Example usage:
print_pyramid(5)
1
22
333
4444
55555
Explanation: We use a loop to iterate from 1 to the given number of rows (inclusive).
Inside the loop, we use the str(i) * i expression to print the number i repeated i times, which generates the pyramid pattern.
Right Triangle (Right Triangle is 90 Degrees)
def print_right_triangle(rows):
for i in range(1, rows + 1):
print("".join(str(j) for j in range(1, i + 1)))
# Example usage:
print_right_triangle(5)
1
12
123
1234
12345
Left Triangle
Right Downward Triangle (Right Triangle is 90 Degrees)
Left Downward Triangle
Double Hill
Reverse Pyramid
Butterfly Diamond
Sandglass
Left Pascal’s Triangle
Right Pascal’s Triangle (Right Triangle is 90 Degrees)
Solve Any Star Pattern Program in Python
Write a Python Program to Print Heart Pattern
def print_heart_pattern():
for row in range(6):
for col in range(7):
if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8):
print("*", end="")
else:
print(" ", end="")
print()
# Example usage:
print_heart_pattern()
** **
* * *
* *
* *
* *
*
The print_heart_pattern() function uses nested loops to print the heart pattern row by row and column by column.
The outer loop (for row in range(6)) iterates over the rows of the pattern, and the inner loop (for col in range(7)) iterates over the columns of the pattern.
The heart pattern is created using logical conditions inside the inner loop. These conditions determine whether to print a star or a space at each position based on the heart shape.
The conditions for printing stars are determined by the equation of the heart shape, which helps form the heart pattern using stars and spaces.