[Tutor] catching errors in calculator script

Christopher Spears cspears2002 at yahoo.com
Tue Sep 18 07:10:05 CEST 2007


I wrote a simple calculator script:

#!/usr/bin/python env

def calculator(n1, operator, n2):
    f1 = float(n1)
    f2 = float(n2)
    if operator == '+':
        return f1 + f2
    elif operator == '-':
        return f1 - f2
    elif operator == '*':
        return f1 * f2
    elif operator == '/':
        return f1 / f2
    elif operator == '%':
        return f1 % f2
    elif operator == '**':
        return f1 ** f2
    else:
        print "Can't perform operation: %s" % operator

print "Welcome to the calculator!"
print "Performs float operations"
print "Enter your problem like so: 5 * 3"
op = raw_input(">>> ")
op_list = op.split()
print calculator(op_list[0], op_list[1], op_list[2])

How do I handle an error that is caused when a
character other than a number is given to the
calculator as one of the operands?  For example, if
the letter 'g' is given to the calculator the
following happens:

io at io-station-1 ./chap5 134> python calculator.py
Welcome to the calculator!
Performs float operations
Enter your problem like so: 5 * 3
>>> g * h
Traceback (most recent call last):
  File "calculator.py", line 26, in ?
    print calculator(op_list[0], op_list[1],
op_list[2])
  File "calculator.py", line 4, in calculator
    f1 = float(n1)
ValueError: invalid literal for float(): g


"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton


More information about the Tutor mailing list