51

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?

6 Answers 6

96

You can use the operator module and a dictionary:

import operator
ops = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.div
}   
op_char = input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)
Sign up to request clarification or add additional context in comments.

3 Comments

For python 3.x the operator.truediv or operator.floordiv should be used instead docs.python.org/3/library/operator.html
additionally, using op_func in this way doesn't work. As the edit queue on this answer is full I've fixed these errors in an answer below (assuming this answer remains ACCEPTED w/ 76 upvotes...)
@RobertHoughton: what do you claim "doesn't work" with this answer? (I don't know what you mean by "the edit queue" either, but that's maybe just something I don't see.)
11

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).

Comments

6

I know this is a really old thread, but I believe at the time people didn't know about the eval function (Maybe it came with Python 3). So here's an updated answer to the question

a = input('enter a value')
b = input('enter a value') 
op = input('enter an operand')
expression = a + op + b # simple string concatenation
result = eval(expression)

If the input is not expected to be valid all the time ast.literal_eval can be used instead. It raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not. Eg. if a, b and op are respectively 5, 10, + then result is 15

4 Comments

It should be expression = a + c + b . btw, using eval for user input is a bad idea. ast.literal_eval is better.
@SilentGuy you're very much right! I've updated my answer
eval wasn't new to Python 3. The reason people aren't suggesting it is because it is not safe to use on user input. It can execute any Python expression (with any side effects) that someone types in. Also, literal_eval only evaluates literals. It cannot evaluate an arithmetic expression like '5+10'.
ast.literal_eval cannot do arithmetic in general, or deal with other operators. It can only handle + and - because of a quirk in the Python grammar.
2

You can use the operator module to create a dictionary. From the Python 3 documentation of that module:

"The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y."

import operator
ops = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv
}   
op_char = input('enter a operand')
a = 1
b = 2
result = ops[op_char](a,b)
print(result)

Comments

1

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.

Comments

0
a = int(input("Give a number for an operation: "))
b = int(input("Give a number for the other operation: "))
operation = input("Choose a math operation (+, -, *, /): ")

if operation == "+":
           result = a + b
elif operation == "-":
            result = a - b
elif operation == "*":
           result = a * b
elif operation == "/":
           result = a / b
else:
           result = "Invalid operation"

print(f"The result is: {result}")

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.