How do I add these numbers? | Sololearn: Learn to code for FREE!
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???

19th Sep 2016, 6:17 AM
The Cool Dude
The Cool Dude - avatar
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))
19th Sep 2016, 9:03 AM
Zen
Zen - avatar
+ 1
print(eval(str(a)+b+str(c)))
19th Sep 2016, 8:41 PM
Ralf