I expect 'True' but get 'None' [duplicate]
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
Solution 1:
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