执行此循环的更优雅,更正确的方法是什么?

时间:2018-01-07 23:07:50

标签: python python-3.x

我的水密度计算中有一个四阶多项式方程。我用一个循环来解决多项式。我用while循环得到了正确的解决方案;不幸的是,我不太了解for-in循环语法,而是将其改为:

# Density of water in kg/m^3 wrt temperature (degC) at 1 atmosphere

def densityWater(tDegC):
    #set up the counter, m
    m = 0

    #set up the data file (linear polynomial equation coefficients)
    #polynomial is of the form ex^4 + dx^3 + cx^2 + bx + a (x = tDegC)
    coeffWaterDensity = (-1.258606246688818E-07, 4.038794321262406E-05, -7.424005247974371E-03, 4.881970120567554E-02, 9.998909544205623E+02)

    densityH2O = 0

    while m < len(coeffWaterDensity):
        densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
        m = m + 1
    return densityH2O

tDegC = input("At what temperature is the water you need the density for? Reply in celsius: ") tDegC = float(tDegC)

print("The density of water at "+ str(tDegC) + " celsius is " + "{:,.1f}".format(densityWater(tDegC)) + " kg/m^3")

但是当我尝试使用for-in而不是while循环时,结果是不正确的

for m in range(len(coeffWaterDensity)):
    densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
    m = m + 1
    return densityH2O

处理此问题的最有效和最正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

你在循环中的return函数结果。 而且不需要增加m,因为for m in range(...)会为你做。

for m in range(len(coeffWaterDensity)):
    densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m)
return densityH2O