[Tutor] Recursion confusion

Todd Stephens tbstep at tampabay.rr.com
Sun Oct 5 13:17:35 EDT 2003


I am trying to learn Python better (and programming in general) and have 
come across something that I am having trouble getting my head around.  
Can someone tell me if my understanding of recursion is correct here?

>>> def factorial(n):
...   if n==0:
...     return 1
...   else:
...     return n*factorial(n-1)

>>> factorial(3)
6

So, what is going on here is this:
3 results in the function returning 3* the result of factorial(2), which 
results in 2 * the result of factorial(1), which results in 1 * the 
result of factorial(0) which results in 1.  So, we have 1*1*2*3.  Now, 
if I were to omit the first condition of n==0, I would get infinite 
recursion, correct?  So, along those lines, for recursion to work, I 
have to include some sort of conditional terminator.  Is that correct?  
If so, I guess I finally understand it (somewhat anyway :-))

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato




More information about the Tutor mailing list