0
votes

So I have an assignment that requires me to print an upside down pyramid made out of asterisks in Python. I know how to print out a normal pyramid but how do I flip it? The height of the pyramid is determined by the input of the user. This is what I have for the normal pyramid:

#prompting user for input
p = int(input("Enter the height of the pyramid: "))


#starting multiple loops
for i in range(1,p+1): 
  for j in range(p-i):
    #prints the spacing
     print(" ",end='')
  #does the spacing on the left side
  for j in range(1,i):
    print("*",end='')
  for y in range(i,0,-1):
    print("*",end='')

  #does the spacing on the right side
  for x in range(p-i):
    print(" ",end='')



  #prints each line of stars
  print("")

Output:

Enter the height of the pyramid: 10
         *         
        ***        
       *****       
      *******      
     *********     
    ***********    
   *************   
  ***************  
 ***************** 
*******************
1
I have Python 3 if that means anything - SilverSymphony
Just change the outermost loop for i in reversed(range(1,p+1)): As simple as that. - tobias_k
@tobias_k Thanks I'm new to Python - SilverSymphony
Seems we can start a library of code to print all those shapes of asterisks used as beginner's exercise: Pyramid, M, Triangels, Diamond, Hollow square - cfi
@cfi I bet that would be a bestseller! But don't forget to include circles! - tobias_k

1 Answers

0
votes

If you want to reverse the pyramid, just reverse the outer loop. Thanks to the magic of python, you can just use the reversed builtin function. Also, you can simplify the body of the loop a little bit using string multiplication and the str.center function.

for i in reversed(range(p)):
    print(('*' * (1+2*i)).center(1+2*p))