0

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
         *         
        ***        
       *****       
      *******      
     *********     
    ***********    
   *************   
  ***************  
 ***************** 
*******************
Raj
  • 1,479
  • 3
  • 15
  • 29
  • I have Python 3 if that means anything – SilverSymphony Oct 16 '15 at 20:59
  • Just change the outermost loop `for i in reversed(range(1,p+1)):` As simple as that. – tobias_k Oct 16 '15 at 21:00
  • @tobias_k Thanks I'm new to Python – SilverSymphony Oct 16 '15 at 21:02
  • 1
    Seems we can start a library of code to print all those shapes of asterisks used as beginner's exercise: [Pyramid](http://stackoverflow.com/questions/33179423/upside-down-pyramid-py), [M](http://stackoverflow.com/questions/28394149/draw-an-m-shaped-pattern-with-nested-loops), [Triangels](http://stackoverflow.com/questions/26352412/python-print-a-triangular-pattern-of-asterisks), [Diamond](http://stackoverflow.com/questions/31364162/print-shape-in-python), [Hollow square](http://stackoverflow.com/questions/16108446/drawing-a-hollow-asterisk-square) – cfi Oct 16 '15 at 21:17
  • 1
    @cfi I bet that would be a bestseller! But don't forget to include [circles](http://stackoverflow.com/q/33171682/1639625)! – tobias_k Oct 16 '15 at 21:27
  • @tobias_k: Actually, I briefly searched for the circle but couldn't find it – cfi Oct 16 '15 at 21:30

1 Answers1

0

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))
tobias_k
  • 81,265
  • 12
  • 120
  • 179