简体   繁体   中英

How to call a function in another function in Python?

I am learning this Python, and I am new to it. I was solving a question which goes like this:

Q1.)Write a Python function, evalQuadratic(a, b, c, x), that returns the value of the quadratic a*x**2+*⋅x+c. This function takes in four numbers and returns a single number. My solution:

def evalQuadratic(a, b, c, x):
    '''
    a, b, c: numerical values for the coefficients of a quadratic equation
    x: numerical value at which to evaluate the quadratic.
    '''
    return ((a*(x*x))+(b*x)+c)

Now this part is fine. There is one more question, which goes like this:

Q2.)Write a Python function, twoQuadratics, that takes in two sets of coefficients and x-values and prints the sum of the results of evaluating two quadratic equations. It does not do anything else. That is, you should evaluate and print the result of the following equation: a1∗x1 2+b1∗x1+c1+a2∗x2 2+b2∗x2+c2 You should use the evalQuadratic function you defined in the "Quadratic" problem of these exercises (you don't need to redefine evalQuadratic in this box; when you call evalQuadratic, our definition will be used).

My Solution:

def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
    '''
    a1, b1, c1: one set of coefficients of a quadratic equation
    a2, b2, c2: another set of coefficients of a quadratic equation
    x1, x2: values at which to evaluate the quadratics
    '''
    for i in range(2):
        return evalQuadratic(a1, b1, c1, x1) + evalQuadratic(a2, b2 ,c2, x2)

I don't know whats wrong with the code, actually its working fine on Canopy IDE on my PC, but returns nothing in the online editor, where I need to give the solution.

Your spec says:

Write a Python function, twoQuadratics, that takes in two sets of coefficients and x-values and prints the sum of the results of evaluating two quadratic equations

Notice the term : it's "prints", not "returns", so what is expected here is very certainly:

def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
    print(evalQuadratic(a1, b1, c1, x1) + evalQuadratic(a2, b2 ,c2, x2))

Here you can take input as a list of dict so your function will be. So your function will be more generic.

enter [{
  'a':2,
  'b':3,
  'c':5,
  'x':10,
 },
 {
   'a':4,
   'b':7,
   'c':5,
   'x':10,
 }]
def my_fun(co_list):
  sum = 0
  for co in co_list:
    sum = sum + evalQuadratic(co['a'], co['b'], co['c'], co['x'])
return sum here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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