0

How can I use an arithmetic operator (input by the user as a string) in an operation? I can print the operation itself, but I want to print the solution!

Here's my clumsy attempt:

# Initialise variables

x = 2
y = 3

# Prompt the user for an arithmetic operator

operator = input("Please enter  *,  /,  +,  or  - : ")

# Calculate the operation

result = (str(x) + operator + str(y))

# Display the result

print(result)

1 Answer 1

4

Use the operator module, which has functions that perform the same operations as your arithmetic operations.

import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}

op = input("Please enter  *,  /,  +,  or  - : ")
result = ops[op](x, y)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Martijn! I had to change 'operator.div' to 'operator.truediv', and then it worked perfectly. I'd upvote your answer, but I don't have enough 'reputation'!
@felixinutero: your acceptance of my answer is reward enough. :-) Glad to have been of help!

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.