使用函数的返回值

时间:2013-10-08 19:49:59

标签: python function return return-value

我最近开始编程,我开始使用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

我该怎么做?

4 个答案:

答案 0 :(得分:2)

# 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获取返回值并将其保存到变量中。然后,您可以使用这些变量来调用下一个函数。

当然,在实际代码中,您应该比我在此示例中更好地命名您的变量。我故意没有调用与函数内部相同的变量来证明你没有必要。

答案 1 :(得分:2)

一种方法是从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

答案 2 :(得分:0)

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

由于我有两个downvotes,我会给你更好的(我希望)解释: 每次返回多个值时,都会返回tuple

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)

我诚实地认为我会返回dict。使用dict,您可以明确,因为您的值具有关键名称。

在你的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"]

答案 3 :(得分:-1)

How do you return multiple values in Python?类似

  1. 以元组(x,y,r ....)或数组形式返回,并分别分配给元组/数组。
  2. 或者将它们分配给类变量并访问它们