如何在我定义的新函数中使用我定义的函数?

时间:2014-02-22 17:38:48

标签: python function while-loop

我定义的第一个功能

def chainPoints(aa,DIS,SEG,H):
#xtuple
    n=0
    xterms = []
    xterm = -DIS
    while n<=SEG:
        xterms.append(xterm)
        n+=1
        xterm = -DIS + n*SEGL
#
#ytuple
    k=0
    yterms = []
    while k<=SEG:
        yterm = H + aa*m.cosh(xterms[k]/aa) - aa*m.cosh(DIS/aa)
        yterms.append(yterm)
        k+=1

但现在我需要第二个函数,它取决于我的第一个函数,特别是列表xterms和yterms。

def chainLength(aa,DIS,SEG,H):
    chainPoints(aa,DIS,SEG,H)

#length of chain
    ff=1
    Lterm=0.
    totallength=0.
    while ff<=SEG:
        Lterm = m.sqrt((xterms[ff]-xterms[ff-1])**2 + (yterms[ff]-yterms[ff-1])**2)
        totallength += Lterm
        ff+=1
return(totallength)

我在没有定义函数的情况下完成了所有操作,但现在我需要为每个部分定义函数。

1 个答案:

答案 0 :(得分:3)

您需要chainPoints()函数返回结果,然后将返回值分配到chainLength()函数中的本地名称:

def chainPoints(aa, DIS, SEG, H):
    #xtuple
    n = 0
    xterms = []
    xterm = -DIS
    while n <= SEG:
        xterms.append(xterm)
        n += 1
        xterm = -DIS + n * SEGL
    #
    #ytuple
    k = 0
    yterms = []
    while k <= SEG:
        yterm = H + aa * m.cosh(xterms[k] / aa) - aa * m.cosh(DIS / aa)
        yterms.append(yterm)
        k += 1

    return xterms, yterms


def chainLength(aa, DIS, SEG, H):
    xterms, yterms = chainPoints(aa, DIS, SEG, H)

    ff = 1
    Lterm = 0.
    totallength = 0.
    while ff <= SEG:
        Lterm = m.sqrt((xterms[ff] - xterms[ff-1]) ** 2 + 
                       (yterms[ff] - yterms[ff - 1]) ** 2)
        totallength += Lterm
        ff += 1

    return totallength

我在chainLength使用了相同的名称,但这不是必需的。