New course! Every coder should learn Generative AI!
Try a free lesson+ 1
How do I add these numbers?
I have three variables a == 5 b == + c == 9 b can be +, -, / or * Can I do something like answer = a (b) c which will do the sum 5 + 9 I know I can use if b == "+": answer = a + b elif b == "-': ........ but it takes lots of code if I add more numbers and symbols Any ideas???
2 Answers
+ 3
You can use switch for a slightly lighter synthax. Oh wait, python doesn't have switch.
You can otherwise make a dictionary with "+", "-", etc. as keys and the corresponding functions (from the operator module) as values.
import operator
def do_op(a, op, b):
ops = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
return ops[op](a, b)
print(do_op(15, "+", 27))
+ 1
print(eval(str(a)+b+str(c)))