[Tutor] Problem with python
Richard D. Moores
rdmoores at gmail.com
Sun Oct 24 14:45:56 CEST 2010
On Wed, Oct 20, 2010 at 03:13, Steven D'Aprano <steve at pearwood.info> wrote:
> Let's start with an easy example: factorial(0). When Python sees
> factorial(0), it does this:
>
> Call factorial with argument 0:
> * if n == 0 <-- this is true, so execute the "if" block:
> return 1
>
> so the function factorial(0) returns the value 1. All that goes on
> behind the scenes. What *we* see is:
>
>>>> factorial(0)
> 1
>
> That part is easy. Now, the recursive part. What does Python do when you
> call factorial(1)?
>
> Call factorial with argument 1:
> * if n == 0 <-- this is false, so execute the "else" block:
> recurse = factorial(n-1)
>
> Here Python is calling a function. It happens to be the same function,
> but Python doesn't care about that, and neither should you. So Python
> simply continues:
>
> Call factorial with argument 1-1 = 0:
>
> Now, we've already seen this above, but Python does the simplest thing
> that could work: it calculates the answer from scratch:
>
I won't quote the whole thing, which should be enshrined somewhere. I
just wanted to note that Steven is a great teacher!
Dick Moores
(teacher, retired)
More information about the Tutor
mailing list