Search code examples
pythonpython-3.xpython-2.7functionuser-input

How to take a user defined function as user input in python?


I am trying to write a program to define user-defined function with return expression as input from user. Suppose a function should return x+y.In python we can do it as---

def f(x,y):
 return x+y

But,i want something like

a=input("enter the function:")
def f(x,y):
  return a
print f(2,3)

If i enter x+y as input of a,it will give 5.How can it be done in Python(without Sympy or raw_function along with eval())?


Solution

  • The Pyparsing lib parses mathematical expressions.

    You can use it like this for example :

    from pyparsing import NumericStringParser
    
    nsp = NumericStringParser()
    print(nsp.eval('2+3')) # 5
    

    You have to replace variables by numeric values.


    In case your really don't want to use external eval library, an application of RPN could be a solution.