我如何避免在这个程序中硬编码我的条件值来打印圣诞树?

2024-10-05 10:01:25 发布

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

在我的程序中,我不知道如何使它,以便我可以打印出这个圣诞树没有硬编码值

z=20
x=1
for i in range(9):
    print(' ' * z + '+' * x + ' ' * z)
    x += 4
    z -= 2
    if z==14 or z==11  or z== 8 or z== 5 or z ==2:
    z+=3
    x-=6
    continue

Tags: orin程序编码forifrangeprint
1条回答
网友
1楼 · 发布于 2024-10-05 10:01:25

比如说:

height = 80
background_width = height * 2
tree_parts = 1
for i in range(height):
    half_background_width = background_width // 2
    background = half_background_width * " "
    tree = tree_parts * "+"
    print(f"{background}{tree}{background}")
    tree_parts += 4
    background_width -= 4
    if (background_width - 4) % 3 == 0:
        background_width += 6
        tree_parts -= 6

更改:

  • Rename the variables更清楚地说明发生了什么
  • 使用f-string显示每一行
  • 使用modulo操作符计算树变窄的断点
  • 从for循环的末尾删除^{},因为这是默认值
  • 使用树的高度来计算所需的宽度,以使较大的树适合

注:其他人在评论中也提到了许多修改

相关问题 更多 >

    热门问题