简体   繁体   English

如何用while创建一棵圣诞树?

[英]How can I create a christmas tree with while?

I am currently working on some code, a student on quarantine and I am trying to solve a problem with a christmas tree but can't quite get into it.我目前正在编写一些代码,一名正在隔离的学生,我正在尝试解决圣诞树的问题,但无法完全解决。

The christmas tree has to be done with "while", I have tried but I only get half the tree.圣诞树必须用“while”完成,我试过但我只得到了一半的树。

Line of code:代码行:

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

What I am getting:我得到了什么:

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

What I want to get:我想得到什么:

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

Here you go.这里是 go。 This will print the tree这将打印树

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

Firstly, your code cannot work since in your while loop the lines are never greater than the maxlines so the statement is False .首先,您的代码无法工作,因为在您的 while 循环中, lines数永远不会大于maxlines ,因此语句为False

As mentioned by all the other people, you are missing spaces.正如所有其他人所提到的,您缺少空格。 Another way as close as possible to your code is this:尽可能接近您的代码的另一种方法是:

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

which gives:这使:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM