Skip to main content
 首页 » 编程设计

python之计算器异常处理,为什么这个例子可以,而我的不行

2025年05月04日16虾米哥

为了进行一些 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 的语义消失了。