[英]How to call a function in another function in Python?
我正在学习这个 Python,而且我是新手。 我正在解决一个这样的问题:
Q1.) 编写一个 Python 函数 evalQuadratic(a, b, c, x),它返回二次方的值 a*x**2+*⋅x+c。 此函数接受四个数字并返回一个数字。 我的解决方案:
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)
现在这部分很好。 还有一个问题,是这样的:
Q2.) 编写一个 Python 函数 twoQuadratics,它接受两组系数和 x 值,并打印计算两个二次方程的结果之和。 它不做任何其他事情。 也就是说,您应该评估并打印以下等式的结果: a1∗x1 2+b1∗x1+c1+a2∗x2 2+b2∗x2+c2 您应该使用您在“Quadratic”问题中定义的 evalQuadratic 函数这些练习中的一部分(您不需要在此框中重新定义 evalQuadratic;当您调用 evalQuadratic 时,将使用我们的定义)。
我的解决方案:
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)
我不知道代码有什么问题,实际上它在我的 PC 上的 Canopy IDE 上运行良好,但在在线编辑器中没有返回任何内容,我需要在其中提供解决方案。
你的规范说:
编写一个 Python 函数 twoQuadratics,它接受两组系数和 x 值,并打印计算两个二次方程的结果之和
注意这个词:它是“打印”,而不是“返回”,所以这里的预期是非常肯定的:
def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
print(evalQuadratic(a1, b1, c1, x1) + evalQuadratic(a2, b2 ,c2, x2))
在这里,您可以将输入作为 dict 列表,以便您的功能成为。 所以你的功能会更通用。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.