Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I expect 'True' but get 'None' [duplicate]

Tags:

python

I have a simple Python script that recursively checks to see if a range of n numbers are factors of a number x. If any of the numbers are not factors I return False, otherwise when the n==1 I would like return True. However I keep returning NoneType and would appreciate suggestions on how to fix this.

#Function
def recursive_factor_test(x, n):
    if n==1:
        return True
    else: 
        if  x % n == 0:
            #print "passed {}".format(n)
            recursive_factor_test(x,n-1)
        else:
            return False

#Example Expecting False
print recursive_factor_test(5041,7)
>>False
#Example Expecting True
print recursive_factor_test(5040,7)
>>None
type(recursive_factor_test(5040,7))
>>NoneType
like image 344
zach Avatar asked Mar 04 '13 20:03

zach


1 Answers

You don't ever return the return value of the recursive call:

if  x % n == 0:
    #print "passed {}".format(n)
    return recursive_factor_test(x,n-1)

When you omit the return statement there, your function ends without a return statement, thus falling back to the default None return value.

With the return there, it works:

>>> print recursive_factor_test(5040,7)
True
like image 128
Martijn Pieters Avatar answered Nov 04 '22 23:11

Martijn Pieters