views:

53

answers:

3

Usual method of applying mathematics to variables is a * b

Is it able to calculate and manipulate two operands like this? a = input('enter a value') b = input('enter a value') op = raw_input('enter a operand') then how do i connect op and two variables a and b?? i know i can compare op to +, -, %, $ and then assign and compute....

but can i do something like a op b , how to tell compiler that op is an operator?? any tweaks possible?

+4  A: 

You can use the operator module and a dictionary:

import operator
ops = {"+": operator.add,
       "-": operator.sub,
       "*": operator.mul,
       "/": operator.div}
op_char = raw_input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)
Matthew Flaschen
yes this module is great, i'm checking it, thanks......
abhilashm86
A: 

The operator module http://docs.python.org/library/operator.html exposes functions corresponding to practically all Python operators. You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).

Luciano Ramalho
+1  A: 

You'll need to compare the user's inputted string to your list of operands by hand. There is no analogue of int() here, since operators are keywords in the language and not values.

Once you've compared that input string to your list of operands and determined the operator that it corresponds to, you can use the Python standard library's operator module to calculate the result of applying the operator to your two operands.

Jordan Lewis