Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function with a variable to be defined on later code [duplicate]

Tags:

python

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!!

like image 974
WinnyDaPoo Avatar asked Sep 02 '25 07:09

WinnyDaPoo


2 Answers

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
like image 146
jrmylow Avatar answered Sep 04 '25 20:09

jrmylow


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
like image 29
Bill Lynch Avatar answered Sep 04 '25 21:09

Bill Lynch