使用 while 循环的空心三角形 python

Hollow triangle using while loops python

尝试编写一个程序,要求用户输入高度和字符,然后使用该字符输出一个空心三角形到该高度。试图首先制作一个实心三角形,然后从那里解决它,但到目前为止只能制作一个半三角形。 此外,仅使用 for 循环而不使用 '*' 运算符

H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
    C = "*"

rows = 1
count = 0
while rows <= H:
    spaces = 0
    while spaces <= (H - rows):
        print(" ", end="")
        spaces += 1
    count = 0
    while count < rows:
        print(C, end="")
        count += 1
    print()
    rows += 1

结果是:

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

我的目标是:

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

如有任何帮助,我们将不胜感激!


稍微改变了你的脚本:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
    C = "*"

rows = 1
count = 0
while rows <= H:
    spaces = 0
    while spaces <= (H - rows):
        print(" ", end="")
        spaces += 1
    count = 0

    while count < 2*rows-1:
        count += 1
        if count == 1 or count == 2*rows-1 or rows == H:
            print(C, end="")
        else:
            print(" ", end="")
    print()
    rows += 1
  H = int(input("Enter height of triangle: "))
  C = str(input("Character: "))
  for i in range(H):
        for j in range(H - i):
              print(' ', end='')
        for j in range(2 * i + 1):
              if j == 0 or j == 2 * i or i == H - 1:
                    print(C, end='')
              else:
                    print(' ', end='')
        print()

得到空心三角形的方法是循环打印空格。 如果观察所需的输出,您会发现除了顶行和底行外,每行只有 2 个星号 (*)。这意味着您需要一个处理空格的逻辑。

有几种编写逻辑的方法,例如将每个垂直的两半视为固定长度的块并仅改变星号的位置或实际计算每行的空间。您可以在方便的时候探索不同的方法来实现您的需求。我会提出一个解决方案。

H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
    C = "*"

rows = 1
count = 0
while rows < H:
    str = ""
    for i in range(H - rows):
        str += " "
    str += C

    if rows > 1:
        for i in range(2 * rows - 3):
            str += " "
        str += C 

    print(str)
    rows += 1

str = ""
for i in range(2 * H - 1):
    str += C
print(str)

我已经更改了检查字符的方法。你不应该允许长度超过 1 的字符。否则,间距会弄乱

这些练习旨在让您理解逻辑并熟悉操作代码,因此请尝试不同的变体

这可能不是最优化的解决方案,但请记住,打印通常很慢,因为它必须与外围设备(显示器)交互,因此请尽可能尝试批量打印。这提高了速度

已经有答案了,但考虑到我做这个小程序很开心,而且我们的解决方案不一样:

H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
    C = "*"

rows = 0
while rows <= H:
    cols = 0
    if rows == H:
        while cols <= H*2:
            print(C, end="")
            cols += 1
    else:
        while cols <= H*2:
            if rows + cols == H or cols - rows == H:
                print(C, end="")
            else:
                print(" ", end="")
            cols += 1
        print()
    rows += 1

请注意,我是用 f​​or 循环执行此操作的,只是换成了 while 循环以将其粘贴到此处。