[Tutor] Advanced Calculator Program...

Brian van den Broek bvande at po-box.mcgill.ca
Sun Feb 20 00:09:19 CET 2005


. Sm0kin'_Bull said unto the world upon 2005-02-19 16:15:
> 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)
> 
> 
> I wrote this but, Error occurs
> 
> print "Please input data"
> number1 = int(raw_input("\nNumber1: "))
> sign = (raw_input("\nMathsmetics Sign: "))
> number2 = int(raw_input("\nNumber2: "))
> 
> total = number1 sign number2
> print number1, sign, number2, '=', total
> 
> please help me
> 
> 
> 
> Cheers! :)

Hi,

what are you expecting this line:

total = number1 sign number2

to do?

>>> total = number1 sign number2
SyntaxError: invalid syntax

The Python interpreter reads the line and says 'Ah, total should equal
number1 -- hey, wait, what I am supposed to do with this other stuff
like sign?'

So, you've got to figure a way to tell the interpreter just how you
want these things combined.

Following the sort of approach you have started with, you've got some
integers and a mathematical operation sign, and you want to *eval*uate
their combination somehow. That suggests

>>> eval('5 + 6')
11

So, this code will work (tested!):

<code>
print "Please input data"
number1 = raw_input("\nNumber1: ")
sign = raw_input("\nMathsmetics Sign: ")
number2 = raw_input("\nNumber2: ")

print eval(number1 + sign + number2)
</code>

<output>
IDLE 1.1
>>> ================================ RESTART 
================================
>>>
Please input data

Number1: 42

Mathsmetics Sign: *

Number2: 100
4200
>>>
</output>

But, this isn't a very good approach, in my opinion. For one thing,
eval is dangerous.

I have an alternate suggestion. It uses several things which may be
new to you. And, as you know, I am no expert, so I make no claim this
is the *best* way. I do think it is better but think it likely that
someone else will post a better idea, still.

Anyway, take a look at this code and see if you can work it out. If
not, post again.

<tested code>

import operator

ops_dict = {'+': operator.add, '*' : operator.mul}

def perform_arithmetic():
     print "Please input data"
     number1 = int(raw_input("\nNumber1: "))
     sign = raw_input("\nMathsmetics Sign: ")
     number2 = int(raw_input("\nNumber2: "))

     try:
         result = ops_dict[sign](number1, number2)
     except KeyError:
         raise NotImplementedError, "I don't know the sign '%s'" %sign

     # add output formatting logic as desired

     return result

print perform_arithmetic()

<tested code>

Hope that helps,

Brian vdB



More information about the Tutor mailing list