Curious2learn
Curious2learn

Reputation: 33598

Why does the function not return a value?

Can you please take a look at the function chooseSampleKey and help me understand why it does not always return a value? It returns a value sometimes, and at other times returns None, so you will have to run it a few times. The problem is especially in the branch that I have named problem branch. It seems to me that the code should always return a value, but either I am going wrong somewhere or there is a bug in 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])

Please run the code a few times and you will see the problem described.

Upvotes: 0

Views: 191

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122326

You are not returning a value here:

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

You need to ensure that all paths through your function end at a return statement.

Otherwise Python will return None which is the default return value for all functions (i.e., when no return statement has been written).

Upvotes: 6

Related Questions