Python函数参数中的数学符号?

Mar*_*s Y 1 python math symbols sign function

我想知道是否有办法在函数参数中添加数学符号。

def math(x, y, symbol):
      answer = x 'symbol' y
      return answer
Run Code Online (Sandbox Code Playgroud)

这是我的意思的一个小例子。

编辑:这是整个问题

def code_message(str_val, str_val2, symbol1, symbol2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code < ord('Z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code > ord('z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code > ord('A'):
                code symbol2= key
                str_val2 += str(chr(code))
            elif code < ord('a'):
                code symbol2= key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2
Run Code Online (Sandbox Code Playgroud)

我需要多次调用该函数,但有时第一个符号使用 +/-,有时第二个符号使用 +/-

原始代码:

def code_message(str_val, str_val2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code < ord('Z'):
                code -= key
                str_val2 += str(chr(code))
            elif code > ord('z'):
                code -= key
                str_val2 += str(chr(code))
            elif code > ord('A'):
                code += key
                str_val2 += str(chr(code))
            elif code < ord('a'):
                code += key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2
Run Code Online (Sandbox Code Playgroud)

Moi*_*dri 5

您不能将运算符传递给函数,但您可以传递operator库中定义的运算符函数。因此,你的函数将是这样的:

>>> from operator import eq, add, sub
>>> def magic(left, op, right):
...     return op(left, right)
...
Run Code Online (Sandbox Code Playgroud)

例子

# To Add
>>> magic(3, add, 5)
8
# To Subtract
>>> magic(3, sub, 5)
-2
# To check equality
>>> magic(3, eq, 3)
True
Run Code Online (Sandbox Code Playgroud)

注意:我使用 function asmagic而不是math因为它math是默认的 python 库,并且使用预定义的关键字不是一个好习惯。