如何编写更好的“树”(python)

时间:2018-11-18 15:30:42

标签: python-3.x

我是编码方面的新手,我得到了一份作业:

您要求用户输入一个随机数字,该数字表示“圣诞树”的大小。树干不包括在树的大小中。 示例: 大小= 5 (5是用户输入的“输入数字”。) 然后在终端中看到以下内容: enter image description here

我想我差不多完成了,但是我只需要更多帮助。

所以,这是我到目前为止所做的:

def print_spruce(n):
   for i in range(1, n+1, 2): 
          print (" " *(n-i) + "X"*(2*i-1))
          print (" " * (n-1) + "X")
n = int(input("Write the size of the spruce:"))
print_spruce(n+1)

终端:

enter image description here

有人可以给我小费/建议/任何帮助/特定帮助来完成此操作。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的问题是您在每个循环中绘制树干,只需将树干绘制代码从for循环中移出,它仅在最后应绘制一次。另外,在for循环中应使用1步而不是2步,并且在调用print_spruce()时n + 1无效。

尝试一下:

def print_spruce(n):
    for i in range(1, n+1):
        print (" " *(n-i) + "X"*(2*i-1))
    print (" " * (n-1) + "X")
n = int(input("Write the size of the spruce:"))
print_spruce(n)