[Tutor] catching errors in calculator script
Alan Gauld
alan.gauld at btinternet.com
Tue Sep 18 09:50:59 CEST 2007
"Christopher Spears" <cspears2002 at yahoo.com> wrote
>I wrote a simple calculator script:
>
> #!/usr/bin/python env
>
> def calculator(n1, operator, n2):
> f1 = float(n1)
> f2 = float(n2)
You probably shouldn't do this since it forces all
your results to be floats even if the two arguments
are integers. Its better to get the client of the
function to decide whjat typres they want to use
and let the function depend on duck typing to work.
> if operator == '+':
> return f1 + f2
...etc
> else:
> print "Can't perform operation: %s" % operator
You could raise an OperatorError exception here
instead of printing which would make the code
more reusable (eg in a GUI). You would have to
define the exception of course, but thats easy:
class OperatorError(Exception): pass
>
> op = raw_input(">>> ")
> op_list = op.split()
This is the best place to convert the data and catch
any errors
> 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
And the type of error to catch is a ValueError.
So just wrap the call to calculator (or your convertions)
in a try/except
try: print calculator( float(op_list[0]), op_list{1], op_list[2])
except ValueError: print "invalid values, try again'
except OperatorError: print 'invalid operator, try again'
Take a look at my tutorial topic on handling errors for more.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list