[Tutor] Recursion confusion
Erik Price
erikprice at mac.com
Sun Oct 5 14:09:11 EDT 2003
On Sunday, October 5, 2003, at 01:17 PM, Todd Stephens wrote:
> 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 :-))
That is all correct.
Erik
More information about the Tutor
mailing list