I am making a function on python3 that solves ax^2+bx+c so a quadratic equation
My code looks like this:
def quadratic(a, b, c):
return a*x**2 + b*x + c
But it wont let me do this because x is undefined. I want to take the argument x on a test code that looks like this:
def testQuadratic(a, b, c, x):
try:
return quadratic(a, b, c)(x)
except TypeError:
return None
Can anyone tell me how I can fix this? Thank you!!
You can make use of the fact that Python supports first-class functions, that can be passed into and returned from other functions.
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
Your quadratic function should... return a function!
def quadratic(a, b, c):
def calculate_quadratic(x):
return a*x**2 + b*x + c
return calculate_quadratic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With