[Tutor] Re: Tutor Digest, Vol 1, Issue 2646

RASTM2 at aol.com RASTM2 at aol.com
Sat Aug 9 03:15:47 EDT 2003


Johnathan H said,

> Can anyone help explain them to me?? 
> 
> This example gives the factorial of a number 
> 
> def fact(n):
>  r=1
>  while n >0:
>    r=r*n
>    n=n-1
>  return r 
> 
line code          # Literally spoken   
1)    def fact(n):         # define a function called fact and let me be
                         # able to set one of the variables called "n"
2)      r = 1         #  this variable "r" is set to 1 every time we call 
fact(n) into play   
                             
3)      while n>0: # so long as this statement is true, "n greater than 0" ,
                           # do the indented lines next, otherwise pass the 
indented lines 
4)          r=r*n   # make my new "r" value equal to my old "r" value times 
                             #the value of "n", then
5)          n=n-1  # make my new "n" value equal to my old "n" value  minus 1
                          # then check the while statement again since this 
is the last 
                          # indented line of the while block, 
                          # if it's still true then do this block again
    
6)       return r      # we reach this statement when n is no longer greater 
than 0 
                         # n must be equal or less than 0
                     # so the value that is currently in r gets "return"ed 
                         # in this case, since you are in the interpreter 
window, 
                         # this will print the value of r after the function 
call fact(n)
>>> fact(5)
120

which is 5*4*3*2*1 = 120

If we call fact(5), then the first time thru the while loop r = 1 and n = 5
since n(5) is greater than 0, we get to go to line 4) 
this is where r picks up it's first new value. r = r * n is really 5 = 1 * 5
But you say how can r have two values? This is not the math I learned in 
school!
This statement is really the result of a great short cut for convienience.
It stems from something like,
c = b + a
b = c 
...but please don't think like this!
r = r * n will make so much sense to you after a while that I ashamed to show 
you
that last bit. 
You should try to follow the fact(n) code all the way through, now.
This will give you great insite as to how the power(x,y=2) works.
What I will say about that one is that you can call it lots of ways.
Try power(2), then power(2,3), then power(2,4).... and so on for a hint.
The "y=2" part is a default value for "y". This means that if you don't give 
the
function a "y" value it will always use a 2. 


Good Luck. Johnathan
I hope you enjoy programming, Python, and the good folks of the Tutor list.
Ray St. Marie
Rastm2@<removethistoreachme>users.sourceforge.net 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030809/1b5a307c/attachment.htm


More information about the Tutor mailing list