使用函数的返回值

我最近开始编程,并开始使用python。 我的问题是:如何在另一个函数中使用函数的结果?

def eklid(p, a, b,):
    x = [1, 0]
    y = [0, 1]
    r = [a, b]
    q = [0]
    n = 0
    while r[n+1] != 0:
        q.append(r[n] // r[n+1])
        r.append(r[n] % r[n+1])
        x.append(x[n] - x[n+1] * q[n+1])
        y.append(y[n] - y[n+1] * q[n+1])

        if p == 0:
            print(r[n], "=", r[n+1], "*", q[n+1], "+", r[n+2])
        elif p == 1:    # extended print
            print(r[n+2], "t", x[n+2], "t", y[n+2], "t", r[n+2], "=", a, "*", x[n+2], "+", b, "*", y[n+2])
        elif p == -1:
            k =1
        else:
            print("wrong input")
        n += 1
    return x, y, r, q, n,

我有这个函数eklid() ,我想在这个函数中使用xr

def cong_solv(x, r, b,):
    result = x/r
    int_result = int(result)
    return int_result

我怎样才能做到这一点?


# Here, a=x, b=y, c=r, d=q, e=n
a, b, c, d, e = eklid(h, i, k)

# Assuming based on your function definitions you want the
# same value as the third argument
final_result = cong_solv(a, c, k)

您从eklid获取返回值并将其保存到变量中。 然后使用这些变量来调用下一个函数。

当然,在一个真实的代码中,你应该比你在这个例子中给出的变量名称更好。 我故意没有将这些变量与函数内部的相同名称进行调用,以证明您不必这样做。


一种方法是从cong_solv()函数内部调用eklid()函数。 像这样的东西应该工作:

def cong_solv(x, r, b):
   p = "foo"
   b = "bar"
   x, y, r, q, n = eklid(p, a, b)

   result = x/r 
   int_result = int(result) 
   return int_result

在python中,当你返回多个变量时,它返回一个元组。 您可以通过其索引(returned_value [0],returned_value [1])检索值,或像Mike Driscoll所说的(a,b,c,d = eklid(h,i,k))解开元组。

既然我得到了两个赞成票,我会给你更好的(我希望)解释:每次你返回多个值,它都会返回一个元组。

def my_function():
   a = 10
   b = 20
   return a, b

print type(my_function()) # <type 'tuple'>

但是,如果你只返回一个值:

def my_function():
    a = 10
    return a

print type(my_function()) # <type 'int'>

所以如果你想使用你的价值,你可以:

像这样解压元组值

a, b = my_function()

这样,您可以按照您在my_function中返回的相同顺序获取返回值。

重写你的代码,你可以简单地做:

a, b, c = eklid(10, 20, 30) # it will return a tuple

并调用你的其他功能:

cong_solv(a, b, 20)

在我诚实的意见,我会返回一个字典。 随着字典你可以是明确的,因为你的价值有关键的名字。

在你的eklid返回函数中:

return d # d = {"what_x_means": x,
         #      "what_y_means": y,
         #      "what_r_means": r,
         #      "what_q_means": q, 
         #      "what_n_means": n}

并检索其关键字:

d["what_x_means"]
d["what_r_means"]
链接地址: http://www.djcxy.com/p/53139.html

上一篇: Use return value of a function

下一篇: Triangle in python