In this article, we will go over different ways to generate pyramids and patters in Python.
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 XXXXXX
Half 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 XXXXXXXXXXX
Reversed pyramid
def inverted_pyramid(rows):
for i in reversed(range(rows)):
print(' '*(rows-i-1) + '*'*(2*i+1))
inverted_pyramid(6)
Output
*********** ********* ******* ***** *** *