为了进行一些python的实践,我决定研究计算器教程。这是非常基本的,因此我决定在用户​​输入垃圾时对其进行异常处理。尽管仍然可以正确使用该程序,但在废话中打孔仍会导致程序崩溃,然后进入
这是我的代码:

loop = 1

choice = 0

while loop == 1:
    #print out the options you have
    print "Welcome to calculator.py"

    print "your options are:"

    print " "
    print "1) Addition"
    print "2) Subtraction"

    print "3) Multiplication"

    print "4) Division"
    print "5) Quit calculator.py"
    print " "

    choice = input("choose your option: ")
    try:
        if choice == 1:
            add1 = input("add this: ")
            add2= input("to this: ")
            print add1, "+", add2, "=", add1+ add2
        elif choice == 2:
            sub1 = input("Subtract this ")
            sub2 = input("from this")
            print sub1, "-", sub2, "=", sub1 - sub2
        elif choice == 3:
            mul1 = input("Multiply this: ")
            mul2 = input("with this: ")
            print mul1, "x", mul2, "=", mul1 * mul2
        elif choice == 4:
            div1 = input("Divide this: ")
            div2 = input("by this: ")
            if div2 == 0:
                print "Error! Cannot divide by zero!  You'll destroy the universe! ;)"
            else:

                print div1, "/", div2, "=", div1 * div2
        elif choice == 5:
            loop = 0
        else:
            print "%d is not valid input. Please enter 1, 2 ,3 ,4 or 5." % choice

    except ValueError:
        print "%r is not valid input.  Please enter 1, 2, 3, 4 or 5." % choice
    print "Thank you for using calculator.py!"


现在,虽然我在这里找到了可用的答案:Error Handling Variables in a calculator program, Error handling numbers are fine

我想知道为什么我的代码不起作用。 python是否要在函数中进行异常处理?这就是我从中得到的氛围。

最佳答案

在Python 2中(您正在使用的),无论用户输入什么内容,input均将其视为Python代码。因此,input可以引发许多不同的异常,但很少出现ValueError

更好的方法是使用raw_input接受您的输入,它返回一个字符串,然后转换为所需的类型。如果输入无效,则将引发ValueError

>>> x = int(raw_input("enter something: "))
enter something: sdjf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'sdjf'


注意:在Python 3中,input假定使用Python 2的raw_input语义,而raw_input消失了。

关于python - 计算器异常处理,为什么此示例有效,但我的无效?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10852653/

10-12 22:09
查看更多