如何从数字中过滤出字母

时间:2019-10-29 20:51:19

标签: python-3.x

我试图创建一个程序来计算梯形的面积,并拒绝字母,直到用户输入数字为止,但是当我输入所有值时,它会在底部抛出错误。

    print("Enter 'x' to exit.")
    starter = input("Press any key except 'x' to continue: ")
    if starter == 'x':
        break
    else:
        print("\nCalculating area of a trapezoid")
        base_1 = 5
        base_2 = 6
        height = input('Height of Trapezoid: ')
        while not height.isdigit():
            height = input("Error. Please input height as a positive number: ")

        base_1 = input('Base one value: ')
        while not base_1.isdigit():
            base_1 = input("Error. Please input base one as a positive number: ")

        base_2 = input('Base two value: ')
        while not base_2.isdigit():
            base_2 = input("Error. Please input base two as a positive number: ")

        print("the area of the trapezoid is: " + str(area = ((base_1 +base_2)/2)*height))

我收到的典型错误。

Traceback (most recent call last):
  File "P:\$College Class Notes\Python\First Project.py", line 78, in <module>
    print("the area of the trapezoid is: " + str(area = ((base_1 +base_2)/2)*height))
TypeError: unsupported operand type(s) for /: 'str' and 'int'

1 个答案:

答案 0 :(得分:0)

即使用户正在输入数字,input()也会返回一个字符串。您需要将它们自己转换为整数。

    base_1 = input('Base one value: ')
    while not base_2.isdigit():
        base_1 = input("Error. Please input base one as a positive number: ")
    base_1 = int(base_1)

此外,无需在打印语句中设置area = ((....))。那实际上是无效的语法。您只需删除area =即可使用,但是为了使代码更简洁,我将您的area分配移到了印刷品之外。

area = ((base_1 +base_2)/2)*height
print("the area of the trapezoid is: " + str(area))

为了获得浮点数,我只是将其放在try / catch中。您可以将while条件设置为是否设置了base_1,因为如果引发异常,仍然不会设置base_1。

base_1 = None
while not base_1:
    try:
        base_1 = float(input('Please input a number: '))
    except ValueError:
        print('Error. Not a number')