为了进行一些 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!"
现在,虽然我在这里找到了一个有用的答案:计算器程序中的错误处理变量,错误处理数字很好
我想知道为什么我的代码不起作用。python是否想要函数中的异常处理?这就是我从中得到的氛围。