Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

python - Upside Down Pyramid (PY)

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
         *         
        ***        
       *****       
      *******      
     *********     
    ***********    
   *************   
  ***************  
 ***************** 
*******************
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...