簡體   English   中英

如何用while創建一棵聖誕樹?

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

我目前正在編寫一些代碼,一名正在隔離的學生,我正在嘗試解決聖誕樹的問題,但無法完全解決。

聖誕樹必須用“while”完成,我試過但我只得到了一半的樹。

代碼行:

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

我得到了什么:

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

我想得到什么:

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

這里是 go。 這將打印樹

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

首先,您的代碼無法工作,因為在您的 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

這使:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM