2

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())?

2 Answers 2

1

This was actually easy.Suppose u want to evaluate the function at x=2

f1=str(input("Enter the test function:"))
def f(x):
    return eval(f1)
print f(2)

That's it!

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.