绘制直角三角形(Python 3)

新手上路,请多包涵

我有点问题。我试图让这个程序根据用户指定的高度和符号输出一个直角三角形,但是每当我输入所需的符号和高度时,程序都会输出正确的形状,但是是颠倒的。通过反复试验,我在牢牢掌握循环方面遇到了一些困难,这是迄今为止我能想到的最好的方法。请哪位大哥帮帮忙。提前谢谢你。

 triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1

当字符为“*”且高度为 5 时,此代码将返回此输出:

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

输入这些值时的预期输出应该是:

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

原文由 Caliman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

首先你的循环都关闭了;您正在将值分配给 ij 并且不使用它们。

其次,第一个循环没有用。如果您输入 3 个字符,它将重复该块 3 次,但变量 triangle_height 在第一次传递时减少到 0,因此在下一次迭代时不会打印任何内容。只需删除此行

第三:你说你需要反转三角形,所以,不要减少 triangle_height ,而是使用你在 for 循环中分配给 j 的值,而忘记减少变量。由于范围从 0 开始计数,您需要在 print 语句中将其加 1:

 triangle_char = input('Enter a character: ')
triangle_height = int(input('Enter triangle height: '))
print('')

for j in range (triangle_height):
    print((triangle_char) * (j + 1))

我还在 input() 方法中用空格替换了 /n 因为它看起来很糟糕。

原文由 Bruno9779 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个脚本。我假设多个输入字符意味着多个输出三角形。此外, height:0 表示每个三角形中的零线。

我今天学到的棘手的事情是 int("20.0") 没有转换为 20;它引发了一个例外。该代码通过首先转换为 float 来解决这个问题。

 #!/usr/bin/python3

def triangles(characters, height):
    # We could call int(height) here except that int("20.0") for example raises
    # an error even though there is a pretty clear integer value. To get around
    # that, attempt to convert to float first.
    try:
        lines = float(height)
    except ValueError:
        # If we raise here, the error is like: cannot convert to float. That's
        # confusing, so we let it go.
        lines = height

    # If the value can't be converted to int, this raises an error like: cannot
    # convert to int. If it had already converted to float, this rounds down.
    lines = int(lines)

    for character in characters:
        # Loop will execute no times if lines==0, once if lines==1 and so on.
        for line in range(1, lines + 1):
            print(str(character) * line)
        print("")

if __name__ == '__main__':
    try:
        triangles(input("Enter characters: "), input("Enter height: "))
    except ValueError as error:
        print("Couldn't print triangles:", error)

编辑:添加示例输出。

 $ ./triangles.py
Enter characters: jk
Enter height: 8
j
jj
jjj
jjjj
jjjjj
jjjjjj
jjjjjjj
jjjjjjjj

k
kk
kkk
kkkk
kkkkk
kkkkkk
kkkkkkk
kkkkkkkk

$ ./triangles.py
Enter characters: .
Enter height: 3.0
.
..
...

$ ./triangles.py
Enter characters: f
Enter height: 3.7
f
ff
fff

$ ./triangles.py
Enter characters: duff
Enter height: duff
Couldn't print triangles: invalid literal for int() with base 10: 'duff'

原文由 sjjhsjjh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题