简体   繁体   English

如何在python中将用户定义的函数作为用户输入?

[英]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---假设一个函数应该返回 x+y。在 python 中,我们可以这样做---

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())?如果我输入 x+y 作为 a 的输入,它会给出 5.How can be done in Python(没有 Sympy 或 raw_function 以及 eval())?

The Pyparsing lib parses mathematical expressions. Pyparsing库解析数学表达式。

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.如果您真的不想使用外部 eval 库, RPN的应用程序可能是一个解决方案。

This was actually easy.Suppose u want to evaluate the function at x=2这实际上很容易。假设你想在 x=2 处评估函数

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

That's it!就是这样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM