在python 3中返回列表的元素将返回None

时间:2018-03-10 03:01:01

标签: python-3.x return-value

我一直试图理解变量的范围如何在python 3中工作以及对象的可变性概念。这让我感到困惑,因为代码1返回None(即使在之前的行中打印了正确的值),但代码2返回正确的值

代码1

def quick_select(numbers,p,r,i):
    if p == r:
        return numbers[p]
    q = partition(numbers,p,r)
    if i == q:
        print(numbers[q]) # prints the correct Value
        return numbers[q] # returns None
    if i < q:
        quick_select(numbers,p,q-1,i)
    else:
        quick_select(numbers,q+1,r,i)

代码2

def foo(a):
    if a[0] > 15:
        return a[0]/15
    else:
        return a[0]

x = [120,30]
print(foo(x)) # works perfectly fine

1 个答案:

答案 0 :(得分:2)

您对递归感到困惑。这是您的 Code1 块,其评论经过调整以反映实际情况:

def quick_select(numbers,p,r,i):
    if p == r:
        return numbers[p]
    q = partition(numbers,p,r)
    if i == q:
        print(numbers[q]) # prints the correct Value
        return numbers[q] # returns the correct value
    if i < q:
        quick_select(numbers,p,q-1,i) # discards the returned value
    else:
        quick_select(numbers,q+1,r,i) # discards the returned value

    # getting to the end of a function without hitting a return is the same as
    # return None