[英]Upside Down Pyramid (PY)
So I have an assignment that requires me to print an upside down pyramid made out of asterisks in Python. 因此,我有一项作业,要求我打印由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
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
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. 多亏了python的魔力 ,您才可以使用
reversed
内置函数。 Also, you can simplify the body of the loop a little bit using string multiplication and the str.center
function. 同样,您可以使用字符串乘法和
str.center
函数来简化循环的主体。
for i in reversed(range(p)):
print(('*' * (1+2*i)).center(1+2*p))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.