我需要用一个函数创建一个带星号的三角形,但我需要这样做:
*****
****
***
**
*
**
***
****
*****
到目前为止,我有这个,但我最终陷入了无休止的循环。
def triangle (n):
i = 0
x = n + 1
while i<n:
print ("*"*(x))
x = x - 1
i=i+1
if i == n:
while i != 0:
print ("*"*(x))
x = x + 1
i=i-1
return ("*")
n=int(input("How many * would you like to see?"))
答案 0 :(得分:1)
你也可以使用两个Python的range()
函数来执行以下操作:
for length in range(5, 0, -1) + range(2, 6):
print '*' * length
或者使用Python 3:
for length in list(range(5, 0, -1)) + list(range(2, 6)):
print('*' * length)
所以作为一个功能你会:
def triangle(n):
for length in list(range(n, 0, -1)) + list(range(2, n+1)):
print('*' * length)
n = int(input("How many * would you like to see? "))
triangle(n)