[Tutor] example help

Zak Arntson zak at harlekin-maus.com
Fri Aug 8 11:10:37 EDT 2003


> Hey im knew to programing and i got these examples out of the book THE
> QUICK
> PYTHON GUIDE.
>
> This example gives the factorial of a number
>
> def fact(n):
>   r=1
>   while n >0:
>      r=r*n
>      n=n-1
>   return r

The best thing to do is to walk through the routine with a handy variable
value chart. Here's an example for fact(4). Before we start, we know that
4! = 4 * 3 * 2 * 1 = 24. So hopefully, that's what we get on the
walkthrough.

fact(4)
r      n      notes
-      -      -----
1      4      at line 2, r=1
4      4      at line 4, r=r*n
4      3      at line 5, n=n-1
now we go back to line 3, n > 0, so we stay in the while loop
12     3      r = r*n
12     2      n = n-1
back to line 3
24     2      r = r*n
24     1      n = n-1
back to line 3
24     1      r = r*n
24     0      n = n-1
back to line 3, n > 0 ? NO! n is equal to zero, not greater than, so we
kick out of the while loop
24     0      return r

return 24

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em



More information about the Tutor mailing list