Main Tutorials

Python – How to print a Pyramid

A simple Python example to print half and full pyramid, just for fun.


def half_pyramid(rows):
    print('Half pyramid...\n')
    for i in range(rows):
        print('*' * (i+1))

def full_pyramid(rows):
    print('\nFull pyramid...\n')
    for i in range(rows):
        print(' '*(rows-i-1) + '*'*(2*i+1))

def inverted_pyramid(rows):
    print('\nInverted pyramid...\n')
    for i in reversed(range(rows)):
        print(' '*(rows-i-1) + '*'*(2*i+1))

half_pyramid(5)
full_pyramid(5)
inverted_pyramid(5)

Output


Half pyramid...

*
**
***
****
*****

Full pyramid...

    *
   ***
  *****
 *******
*********

Inverted pyramid...

*********
 *******
  *****
   ***
    *

References

  1. Java – How to print a Pyramid

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
mary
5 years ago

Hello, this program prints out a sideways triangle. How do I convert this this to recursion? Thank you. Here is the code in Python:

def sideways_triangle(n):
i = 1
while i 0:
print (‘-‘ * i)
i -= 1

Here is the output:



—-


Savani S
6 years ago

Could you please create the python tutorials ?