This article will review different ways to generate pyramids and patterns in Python. Let’s Master Python Patterns – Create Pyramids and Patterns with Code.
Half pyramid of asterisks
def half_pyramid(rows):
for i in range(rows):
print('*' * (i+1))
half_pyramid(6)Output
*
**
***
****
*****
******An alternate way to generate half pyramid using nested loops in Python.
Program
def half_pyramid(rows):
for i in range(rows):
for j in range(i+1):
print("*", end="") print("")
half_pyramid(6)Output
*
**
***
****
*****
******Half pyramid of X’s
def half_pyramid(rows):
for i in range(rows):
print('X' * (i+1))
half_pyramid(6)Output
X
XX
XXX
XXXX
XXXXX
XXXXXXHalf pyramid of numbers
def half_pyramid(rows):
for i in range(rows):
for j in range(i + 1):
print(j + 1, end="")
print("")
half_pyramid(5)Output
1 12 123 1234 12345
Generating a full pyramid of asterisks
def full_pyramid(rows):
for i in range(rows):
print(' '*(rows-i-1) + '*'*(2*i+1))
full_pyramid(6)Output
*
***
*****
*******
*********
***********Full pyramid of X’s
def full_pyramid(rows):
for i in range(rows):
print(' '*(rows-i-1) + 'X'*(2*i+1))
full_pyramid(6)Output
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
XXXXXXXXXXXReversed pyramid
def inverted_pyramid(rows):
for i in reversed(range(rows)):
print(' '*(rows-i-1) + '*'*(2*i+1))
inverted_pyramid(6)Output
***********
*********
*******
*****
***
*