我正在 python3 上创建一个函数来解决 ax^2+bx+c 所以一个二次方程
我的代码如下所示:
def quadratic(a, b, c):
return a*x**2 + b*x + c
Run Code Online (Sandbox Code Playgroud)
但它不会让我这样做,因为 x 未定义。我想在如下所示的测试代码中使用参数 x:
def testQuadratic(a, b, c, x):
try:
return quadratic(a, b, c)(x)
except TypeError:
return None
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何解决这个问题?谢谢!!
小智 7
您可以利用 Python 支持一流函数的事实,这些函数可以传入其他函数并从其他函数返回。
def make_quadratic(a, b, c):
def f(x):
return a*(x**2) + b*x + c
return f
# You would call the returned function
my_quadratic = make_quadratic(a, b, c)
# You can then call my_quadratic(x) as you would elsewhere
Run Code Online (Sandbox Code Playgroud)