Python Mathematical signs in function parameter?
<p>I would like to know if there is a way to add math symbols into the function parameters. </p>

<pre><code>def math(x, y, symbol):
      answer = x 'symbol' y
      return answer
</code></pre>

<p>this is an small example what I mean. </p>

<p><strong>EDIT:
here is the whole problem</strong> </p>

<pre><code>def code_message(str_val, str_val2, symbol1, symbol2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code &lt; ord('Z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code &gt; ord('z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code &gt; ord('A'):
                code symbol2= key
                str_val2 += str(chr(code))
            elif code &lt; ord('a'):
                code symbol2= key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2
</code></pre>

<p>I need to call the function a number of times but sometimes with a +/- for first symbol and sometimes a +/- for second symbol</p>

<p>ORIGINAL CODE :</p>

<pre><code>def code_message(str_val, str_val2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code &lt; ord('Z'):
                code -= key
                str_val2 += str(chr(code))
            elif code &gt; ord('z'):
                code -= key
                str_val2 += str(chr(code))
            elif code &gt; ord('A'):
                code += key
                str_val2 += str(chr(code))
            elif code &lt; ord('a'):
                code += key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2
</code></pre>

<p>Use the corresponding functions, from <code>operator</code> module:</p>

<pre><code>from operator import add
def math(x, y, add):
      answer = add(x, y)
      return answer
</code></pre>

<p>The only way that you can pass a mathematics sign to a function is passing is in string mode, then you'd have two problems, evaluating the sign and the equation as well. So when you are dealing with numbers you better to use a proper functions to does the job directly.</p>

<p>You can also use a dictionary to map the symbols to the corresponding function: </p>

<pre><code>from operator import add, sub, mul
mapping = {"+": add, "-":sub, "*": mul}
def math(x, y, sym):
    try:
        f = mapping[sym]
    except KeyError:
        raise Exception("Enter a valid operator")
    else:
        answer = f(x, y)
        return answer
</code></pre>

python function math symbols sign