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



我目前正在编写一些代码,一名学生正在隔离中,我正试图解决圣诞树的问题,但无法完全解决。

圣诞树必须用";而";,我试过了,但我只得到了半棵树。

代码行:

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

我得到的:

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

我想要得到的:

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

首先,您的代码无法工作,因为在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

它给出:

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

开始吧。这将打印树

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

最新更新