我的初学python项目(计算器)输入有问题

时间:2016-09-28 12:31:45

标签: python

每当我测试我的计算器以查看它如何处理非数字的输入时,它会标记一个ValueError。更准确地说,这个" ValueError:无法将字符串转换为浮点数:' a'"'''我试图修改这个,所以有一个处理非整数的解决方案但无济于事...非常感谢帮助。

到目前为止,这是我的代码:

print("1. ADDITION ")
print("2. MULTIPLICATION ")
print("3. TAKEAWAY ")
print("4. DIVISION ")

Operator = int(input("please enter one of the numbers above to decide the operator you want. "))

while Operator > 4:
    print("Please select a number from the options above. ")
    Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
    if Operator != (1 or 2 or 3 or 4):
        print("please enter one of the options above. ")
        Operator = int(input("please enter one of the numbers above to decide the operator you want. "))
    continue

while True:
    Num1 = float(input("Please enter first number. "))
    if Num1 == float(Num1):
        print("thanks! ")
    elif Num1 != float(Num1):
        Num1 = float(input("Please enter first number. "))
    break

while True:
    Num2 = float(input("Please enter second number. "))
    if Num2 == float(Num2):
        print("thanks ")
    elif Num1 != float(Num1):
        Num1 = float(input("Please enter first number. "))
    break

3 个答案:

答案 0 :(得分:1)

您正在寻找异常处理。 像这样的Smthng:

input = 'a'
try:
    int(a)
except ValueError:
    print 'Input is not integer'

答案 1 :(得分:0)

请阅读处理例外情况的文档:

https://docs.python.org/2/tutorial/errors.html#handling-exceptions

表示浮动:

try:
    x = float(input("Please enter a number: "))
    break
except ValueError:
    print "Oops!  That was no valid number.  Try again..."

答案 2 :(得分:0)

注意:您应根据PEP8将变量命名为小写,请参阅:What is the naming convention in Python for variable and function names?

如果您想要在没有ValueError之前重试输入,请将其置于循环中:

print("Please select a number from the options above.")
while True:
    try:
        operator = int(input("please enter one of the numbers above to decide the operator you want: "))
    except ValueError:
        print("Sorry, not a number. Please retry.")
    else:
        if 1 <= operator <= 4:
            break
        else:
            print("Sorry, choose a value between 1 and 4.")

注意:在Python 3.x中使用input或在Python 2.7中使用raw_input

1. ADDITION
2. MULTIPLICATION
3. TAKEAWAY
4. DIVISION
Please select a number from the options above.
please enter one of the numbers above to decide the operator you want: spam
Sorry, not a number. Please retry.
please enter one of the numbers above to decide the operator you want: 12
Sorry, choose a value between 1 and 4.
please enter one of the numbers above to decide the operator you want: 2