For a bit of python practice, I decided to work on a calculator tutorial. It was very basic, so I decided to give it exception handling in the event a user enters in garbage. While proper use of the program still works, punching in crap still causes it to crash, and entering
Here is my code:
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!"
Now while I found an useable answer here: Error Handling Variables in a calculator program, Error handling numbers are fine
I was wondering why my code didn’t work. Does python want the exception handling in a function? That’s the vibe I’m getting from it.
In Python 2 (which is what you are using)
inputevaluates as Python code whatever the user enters. Because of thisinputcan raise many different exceptions, but rarely aValueError.Better would be to accept your input with the
raw_inputwhich returns a string, and then cast to the expected type. If the input is invalid it will then raise aValueError:Note: In Python 3
inputassumes the semantics of Python 2’sraw_inputandraw_inputgoes away.