In this article, we'll take a look at
Show
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
1 2 3 4 5 |
def half_pyramid(rows): for i in range(rows): print('*' * (i+1)) half_pyramid(6) |
Output
1 2 3 4 5 6 |
* ** *** **** ***** ****** |
An alternate way to generate half pyramid using nested loops in Python.
Program
1 2 3 4 5 6 |
def half_pyramid(rows): for i in range(rows): for j in range(i+1): print("*", end="") print("") half_pyramid(6) |
Output
1 2 3 4 5 6 |
* ** *** **** ***** ****** |
Half pyramid of X’s
1 2 3 4 5 |
def half_pyramid(rows): for i in range(rows): print('X' * (i+1)) half_pyramid(6) |
Output
1 2 3 4 5 6 |
X XX XXX XXXX XXXXX XXXXXX |
Half pyramid of numbers
1 2 3 4 5 6 7 |
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 2 3 4 5 |
1 12 123 1234 12345 |
Generating a full pyramid of asterisks
1 2 3 4 5 |
def full_pyramid(rows): for i in range(rows): print(' '*(rows-i-1) + '*'*(2*i+1)) full_pyramid(6) |
Output
1 2 3 4 5 6 |
* *** ***** ******* ********* *********** |
Full pyramid of X’s
1 2 3 4 5 |
def full_pyramid(rows): for i in range(rows): print(' '*(rows-i-1) + 'X'*(2*i+1)) full_pyramid(6) |
Output
1 2 3 4 5 6 |
X XXX XXXXX XXXXXXX XXXXXXXXX XXXXXXXXXXX |
Reversed pyramid
1 2 3 4 5 |
def inverted_pyramid(rows): for i in reversed(range(rows)): print(' '*(rows-i-1) + '*'*(2*i+1)) inverted_pyramid(6) |
Output
1 2 3 4 5 6 |
*********** ********* ******* ***** *** * |
Leave a Comment