Answer the question
In order to leave comments, you need to log in
The function does not accept operations?
def arithmetic(a,b,operation):
if operation=='+':
print(a+b)
elif operation=='-':
print(a-b)
elif operation=='*':
print(a*b)
elif operation=='/':
print(a/b)
else:
print('Unknown operation')
arithmetic(1,2,*)
Ошибка:
Traceback (most recent call last):
File arithmetic.py, line 14
arithmetic(1,2,*)
^
SyntaxError: invalid syntax (unnamed star argument)
Answer the question
In order to leave comments, you need to log in
As an operation argument, you can take an operator as a function from the operator module , which, in my opinion, will be better.
import operator
def arithmetic(a: int, b: int, operation):
if operation not in (operator.add, operator.sub, operator.mul, operator.truediv):
print('Unknown operation')
else:
print(operation(a, b))
arithmetic(1, 2, operator.mul)
operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
arithmetic(1, 2, operators['*'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question