Reputation: 105
I'm trying to build a sample calculator in Python. It's expected output for calculate(2, 3, -)
should be -1.
However, I have a hard time defining the operator.
if operator == +:
will return a syntax error, but when I do
if operator == '+':
I need to write something like calcuate(3, 4, '+')
to work.
Here are
def calculate(x, y, operator):
if operator == '+':
print (x + y)
elif operator == '-':
print (x - y)
elif operator == '*':
print (x * y)
elif operator == '/':
print (x / y)
Is it possible for me to get rid of the required apostrophes?
Upvotes: 2
Views: 277
Reputation: 17166
As the comments indicate you can not simply pass +, -, div.
Another option that would simplify your code is to use the operator module
Code refactoring using operator module
# We obtain operators we will use from operator module
from operator import add, sub, mul, pow
from operator import truediv as div
def calculator(x, y, op):
" Calculator applies the passed-in operator to arguments "
return op(x, y)
# Tests
print(calculator(5, 3, add))
print(calculator(5, 3, sub))
print(calculator(5, 3, mul))
print(calculator(5, 3, div))
print(calculator(5, 3, pow))
Using Your Original String Input
As @JLPeyret suggests, operators make it easier to use a dictionary for the logic for which operation to choose.
def calculator(x, y, op):
" Calculator applies the passed-in operator to arguments "
d = {'+', add,
'-', sub,
'*', mul,
'/', div,
'**', pow}
return d[op](x, y)
# Tests
print(calculator(5, 3, '+'))
print(calculator(5, 3, '-'))
print(calculator(5, 3, '*'))
print(calculator(5, 3, '/'))
print(calculator(5, 3, '**'))
Outputs in both cases
8
2
15
1.6666666666666667
125
Upvotes: 2