hello, its me again :-)
Julius Welby
jwelby at waitrose.com
Wed May 23 07:06:03 EDT 2001
Just for fun, this one handles multi digit input and catches divide by zero.
It looks like it could be made much shorter by iterating through a list of
operators.
(If nothing else, you may want to use string.lower in your script to get rid
of the 'X' versus 'x' distiction)
#######
import string
e = raw_input('Enter expression --> ')
e = string.lower(e)
ans = 'Invalid Operator'
try:
sp = string.split(e, '*')
ans = float(sp[0]) * float(sp[1])
except:
pass
try:
sp = string.split(e, 'x')
ans = float(sp[0]) * float(sp[1])
except:
pass
try:
sp = string.split(e, '/')
if float(sp[1]) == 0:
ans = "Divide by zero error!"
else:
ans = float(sp[0]) / float(sp[1])
except:
pass
try:
sp = string.split(e, '+')
ans = float(sp[0]) + float(sp[1])
except:
pass
try:
sp = string.split(e, '-')
ans = float(sp[0]) - float(sp[1])
except:
pass
print ans
More information about the Python-list
mailing list