I wrote a function like this, the op gives a operation sign which like '+','-','*','/' or more, the code “adds” everything use the given operator,
Here is the code:
def arithmetic(op,*args):
result = args[0]
for x in args[1:]:
if op =='+':
result += x
elif op == '-':
result -= x
elif op == '*':
result *= x
elif op == '/':
result /= x
return result
Is there a way i can use the +,-,*,/ directly? So I don’t have to write an If-Else statement?
I think you’re looking for the builtin
reducefunction combined withoperator:Of course, if you want to do this using strings, you can map the strings to an operation using a dict:
then it becomes: