为什么函数不返回值?

时间:2013-12-03 22:10:22

标签: python

请您查看函数chooseSampleKey并帮助我理解为什么它不总是返回值?它有时会返回一个值,而在其他时候返回None,所以你必须运行它几次。问题尤其在我命名为问题分支的分支中。在我看来,代码应该总是返回一个值,但要么我在某处出错或者Python中存在错误。

import random

peeps = {1: [], 2: [], 3: ['A', 'B'], 4: ['C', 'D'], 5: ['E']}

dictkeys = [1, 2, 4, 5]

def chooseSampleKey(peeps, dictkeys):
    if len(dictkeys) > 0:
        sampleKey = random.sample(dictkeys, 1)[0]
        print 'From chooseSampleKey, sampleKey = ', sampleKey
        print "peeps in samplekey: ", len( peeps[sampleKey] )

        if len( peeps[sampleKey] ) > 0:

            # **problem branch**: sampleKey is defined and has a value.
            # the function comes here and prints the following statement
            # with the value of samplekey. However, despite printing 
            # a value for sampleKey in following line, 
            # the print for the function itself prints None, i.e., no 
            # value is returned.

            print "Returning samplekey {0}".format( sampleKey )
            return sampleKey

        else:
            dictkeys.remove(sampleKey)
            chooseSampleKey(peeps, dictkeys)
    else:
        return 0


print chooseSampleKey(peepsTemp, [1, 2, 4, 5])

请运行几次代码,您将看到所描述的问题。

1 个答案:

答案 0 :(得分:6)

您没有在此处返回值:

    else:
        dictkeys.remove(sampleKey)
        chooseSampleKey(peeps, dictkeys)
        # here <-----------
else:
    return 0

您需要确保函数的所有路径都以return语句结束。

否则Python将返回None,这是所有函数的默认返回值(即,当没有写入return语句时)。