1

I would like to know if there is a way to add math symbols into the function parameters.

def math(x, y, symbol):
      answer = x 'symbol' y
      return answer

this is an small example what I mean.

EDIT: here is the whole problem

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

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

ORIGINAL CODE :

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
2
  • 1
    Sorry, could you elaborate a bit more Commented Aug 29, 2016 at 10:50
  • did you mean answer = x "symbol" y? Commented Aug 29, 2016 at 10:51

4 Answers 4

5

You can not pass operator to the function, but however you may pass operator's functions defined in operator library. Hence, your function will be like:

>>> from operator import eq, add, sub
>>> def magic(left, op, right):
...     return op(left, right)
...

Examples:

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

Note: I am using function as magic instead of math because math is default python library and it is not good practice to use predefined keywords.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the corresponding functions, from operator module:

from operator import add
def math(x, y, add):
      answer = add(x, y)
      return answer

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.

You can also use a dictionary to map the symbols to the corresponding function:

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

3 Comments

And what to do with add(x, y) = answer being a syntax error?
answer = add(x,y)
@AnttiHaapala Just, a copy past mistake!
1

I am surprised noone mentioned eval(). Look at the example below:

def function(operator1, operator2, symbol):
    return eval(str(operator1) + symbol + str(operator2))

print(function(2, 3, '+'))      # prints: 5
print(function(2, 3, '-'))      # prints: -1

# Of course you can also "chain" operations, e.g., for 4 + 5 - 6
result = function(function(4, 5, '+'), 6, '-')
print(result)                   # prints 3

# Finally, it also works with string input for the operands so you 
# can read them directly from e.g., user input with `input()`
print(function('2', '3', '+'))  # prints: 5

2 Comments

eval is the function which is never recommended to be used in the program. It will work, but it is not recommended. In fact, according to me, eval functions can anytime may turn into virus and you won't even know what went wrong
@MoinuddinQuadri "With great power comes great responsibility" would be my comment on that.
0

You should first consider that you have to use answer = x symbol y and not the contrary.

Then concerning the use of symbols, you can send the function as a parameter. For the basic operator you might use the operator module.

For example:

import operator

def math(x, y, function):
      return function(x, y)

math(4,5, operator.sub)

You will find in the documentation all the others operations you need.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.