[英]python How to convert the input value into a mathematical function
How to convert an input value into a function!如何将输入值转换为函数!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.实际上,据我所知,您不需要输入 n。
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval() Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2编辑,在重读其他人回答是的之后,它可能想要 eval() 只是你不能写“2 * x ^ 2 - 2 * x + 2”,正确的方法是 x**2 而不是 x^2
You mean (?):你的意思是 (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?还是您的意思是实际更改运营商?
The question as currently posed is mathematically impossible.目前提出的问题在数学上是不可能的。 You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
您定义 x & n 并返回一个 function 您可能希望或可能不希望等同于 n 但它的所有已定义条目。
Still guessing a little at the actual question, but if仍然对实际问题进行了一些猜测,但是如果
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, ie:并且您希望 y 是二次方,即:
y = "a*x**b - c*x + d"
then you can get all them from:那么您可以从以下位置获取所有内容:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow.如果你想要运营商,那么它会变得有点难以遵循。 So we'll cross that bridge if you do need them.
因此,如果您确实需要它们,我们将越过那座桥。
Or, as the others suggest, just use eval()!!或者,正如其他人所建议的那样,只需使用 eval()!
You could try to use eval
.您可以尝试使用
eval
。
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking.我想,你在问。 How to convert an input value into a mathmetical expression?
如何将输入值转换为数学表达式?
If it is so !如果是这样!
use eval() in python在 python 中使用 eval()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.