How do I get a recursive function to return a value other than None?
For example:
def function(depth):
if depth > 0:
function(depth - 1)
else:
return 10
function(5)
returns None, and not 10.
How do I get a recursive function to return a value other than None?
For example:
def function(depth):
if depth > 0:
function(depth - 1)
else:
return 10
function(5)
returns None, and not 10.
Look at your function, when depth > 0, it executes function(depth -1), but it returns nothing (hence None). You must write
def function(depth):
if depth > 0:
return function(depth - 1)
else:
return 10
function(5)
You must return the value from the recursive function.
def function(depth):
if depth > 0:
return function(depth - 1)
else:
return 10
function(5)
EDIT: Sorry, was testing it while it was answered.
Thanks, it worked. Now I am trying to understand why it does. Is it because the first time it executes function(), there is no return statement so it finishes executing the function and returns the default return value of None?
You just have to look at the code: When you call the function what is the argument that is passed in? You can think of each invocation (whether called from 'outside' or from 'inside') as a distinct function. This is the function:
def func(depth):
if depth > 0:
return function(depth - 1)
else:
return 10
So the invocation chain looks like
func(5) returns func(4)
func(4) returns func(3)
func(3) returns func(2)
func(2) returns func(1)
func(1) returns func(0)
func(0) ... takes the other branch of the depth test ... returns 10
So, you can see that for this function, you always get 10 no matter what non-negative argument you pass in. (Beware passing a negative argument though: What will happen?).
More interesting recursive functions do something that is ... more interesting. For instance one of the canonical recursive functions is factorial:
def factorial(num):
try:
assert num == int(num)
except (AssertionError, ValueError):
print ("You must pass an integer parameter")
return None
if num < 0:
return 0 - factorial(-num)
# We know num >= 0 here
if num <= 1:
return num
return num * factorial(num-1)
print ("%d: %d"%(3,factorial(3)))
print ("%d: %d"%(-4,factorial(-4)))
print ("%s: %s"%("moo",factorial("moo")))
print ("%s: %s"%(1.5,factorial(1.5)))
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.