绘制直角三角形(Python 3)

2024-04-27 00:40:18 发布

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

我有点问题。我试图使这个程序输出一个基于用户指定的高度和符号的直角三角形,但每当我输入所需的符号和高度时,程序将输出正确的形状,但颠倒。我一直有一些困难,得到一个坚定的循环和通过反复试验,这是我迄今为止能想到的最好的。有人能帮个兄弟吗。提前谢谢你们。

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时,此代码将返回此输出:

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

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

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

Tags: 用户in程序forinput高度符号range
3条回答

这是剧本。我假设多个输入字符意味着多个输出三角形。另外,高度: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'

您也可以这样做:

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

j = 0;

while j <= triangle_height :
    print triangle_char * j
    j += 1

首先,循环都是关闭的;您将值赋给ij而不使用它们。

第二,第一个循环是无用的。如果输入3个字符,它将重复块3次,但是变量triangle_height在第一次传递时减小为0,因此在下一次迭代中不会打印任何内容。 去掉这条线

第三:你说你需要倒三角形,所以,不要减少for循环中的triangle_height,而是使用你在for循环中对j的赋值,而不要减少变量。 由于范围从0开始计数,您需要在打印语句中向其添加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,因为它看起来很糟糕。

相关问题 更多 >