温馨提示×

用Python代码绘制3种不同的圣诞树

小亿
109
2023-12-22 08:06:59
栏目: 编程语言

以下是三种不同的圣诞树的Python代码:

  1. 实心圣诞树:
def draw_solid_tree(height):
    for i in range(height):
        print(' ' * (height - i - 1) + '*' * (2*i + 1))
    print(' ' * (height - 1) + '|')

# 调用函数绘制实心圣诞树
draw_solid_tree(5)

输出结果:

    *
   ***
  *****
 *******
*********
    |
  1. 空心圣诞树:
def draw_hollow_tree(height):
    for i in range(height):
        if i == height - 1:
            print(' ' * (height - i - 1) + '*' * (2*i + 1))
        else:
            print(' ' * (height - i - 1) + '*' + ' ' * (2*i - 1) + '*')
    print(' ' * (height - 1) + '|')

# 调用函数绘制空心圣诞树
draw_hollow_tree(5)

输出结果:

    *
   * *
  *   *
 *     *
*********
    |
  1. 倒立圣诞树:
def draw_inverse_tree(height):
    for i in range(height, 0, -1):
        print(' ' * (height - i) + '*' * (2*i - 1))
    print(' ' * height + '|')

# 调用函数绘制倒立圣诞树
draw_inverse_tree(5)

输出结果:

*********
 *******
  *****
   ***
    *
    |

0