[Tutor] Advanced Calculator Program...
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sun Feb 20 05:01:09 CET 2005
> > I want to make caculator program which enables me to enter 2numbers
> > and mathsmatics sign and calculates it. I think this is too difficult
> > for newbie like me...
> >
> > Please input data
> >
> > Number1:
> > Mathsmetics Sign:
> > Number2:
> >
> > (Number1) (Sign) (Number2) = (Result)
>
>
> *One* way to solve your problem is, e. g., to use a branching statement
> for checking, which operator is used.
>
> So replace the line
>
> total = number1 sign number2
>
> by something similar to
>
> if sign == "+":
> total = number1 + number2
> elif sign == "-":
> total = numer1 - number2
> ... (for other operators ..)
One variation of this is to turn the 'sign' from a string into a function:
###
import operator
def getOperator(sign):
if sign == '+':
return operator.add
elif sign == '-':
return operator.sub
elif sign == '*':
return operator.mul
elif sign == '/':
return operator.div
else:
raise ValueError, ("I don't know about %s" % sign)
###
We're pulling out functions from the 'operator' module:
http://www.python.org/doc/lib/module-operator.html
If we have this, then we can do:
###
>>> myop = getOperator("+")
>>> myop(3, 17)
20
>>>
>>>
>>> myop = getOperator("*")
>>> myop(42, 17)
714
###
Best of wishes to you!
More information about the Tutor
mailing list