计算器异常处理,为什么这个例子工作但我的不工作?

use*_*649 1 python exception-handling calculator

对于一些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!"
Run Code Online (Sandbox Code Playgroud)

现在我在这里找到了一个可用的答案:错误处理计算器程序中的变量,错误处理数字很好

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

Ste*_*ski 5

在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'
Run Code Online (Sandbox Code Playgroud)

注意:在Python 3中input假定Python 2的语义raw_input并且raw_input消失了.