如何用while创建圣诞树?

2024-09-27 21:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一些代码,我是一名研究检疫的学生,我正试图解决一个圣诞树的问题,但不能完全理解它

圣诞树必须用“while”完成,我已经试过了,但我只得到了一半

代码行:

lines=1
maxlines=9
while lines>=maxlines:
  print (lines*'*')
  lines+=1

我得到的是:

*
**
***
****
*****
******
*******
********
*********

我想要的是:

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

Tags: 代码学生linesprintwhile圣诞树正试图maxlines
3条回答
star = 1 # Star count
maxLines = 9 # Total number of lines
actualLines = 0 # Lines count

while actualLines <= maxLines:

     # print the necessary spaces before the stars   print the stars
     print(str(abs(maxLines - actualLines ) * ' ') + str(star * '*'))

     star += 2 # add 2 stars every new line
     actualLines += 1 # add 1 to the line counting

给你。这将打印树

def tree(n):

    # total spaces
    k = 2 * n - 2

    # number of rows
    i = 0
    while i < n:
        j = 0

        # inner loop for number spaces
        while j < k:
            print(end=" ")
            j = j + 1

        # decrementing k after loop
        k = k - 1

        # number of columns
        j = 0
        while j < i + 1:
            print("* ", end="")
            j = j + 1

        # end line
        print("\r")
        i = i + 1


# Begining
n = 5
tree(n)

首先,您的代码无法工作,因为在while循环中lines永远不会大于maxlines,所以语句是False

正如所有其他人提到的,您缺少空格。另一种尽可能接近代码的方法是:

lines=1
maxlines=9

while lines<=maxlines:
    # print the leading spaces, the left part and the right side of the tree
    print((maxlines-lines)*' '+ lines*'*'+(lines-1)*'*')
    lines+=1

其中:

        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************

相关问题 更多 >

    热门问题