F
F
fckqqpy2021-10-01 13:06:58
Python
fckqqpy, 2021-10-01 13:06:58

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

1 answer(s)
V
Viktor Golovanenko, 2021-10-01
@fckqqpy

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)

If you need to specify operators through symbols, you can create a dictionary in which to store operator symbols and their functions:
operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv
}

arithmetic(1, 2, operators['*'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question