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.

teddypwns 0 Newbie Poster

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.

Gribouillis 1,391 Programming Explorer Team Colleague

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)
```

Beat_Slayer 17 Posting Pro in Training

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.

Edited by Beat_Slayer because: * n/a *

teddypwns 0 Newbie Poster

griswolf 304 Veteran Poster

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)))
```

Edited by griswolf because: * add (correct) examples *

ultimatebuster 14 Posting Whiz in Training

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.