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

asked Nov 23, 2019 at 14:41

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!

answered Jan 26, 2020 at 6:39
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.

answered Nov 23, 2019 at 15:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.