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:
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:
assert num == int(num)
except (AssertionError, ValueError):
print ("You must pass an integer parameter")
if num < 0:
return 0 - factorial(-num)
# We know num >= 0 here
if num <= 1:
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 6 Years Ago by griswolf: add (correct) examples
Need some help with this Array. I am trying to get the sum of the even numbers and the sum of the odd numbers using a for each loop. I know the answers to what I am trying to achive are sum of even = 84 and the sum of ...
I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...