defining functions
Michael Chermside
mcherm at destiny.com
Wed Feb 13 10:31:51 EST 2002
Patio87 at aol.com wrote:
> Thanks for your reply, but I had another question. I dont
> understand how factorial(n) gets the value of two? And does The 'n' have
> 1 assigned to by default?
Okay, try this simpler example:
>>> def threeTimes(x):
print 'x is now %i' % x
if x == 0:
return 0
else:
return 3 + threeTimes(x-1)
After writing this, what is the value of 'x'?
>>> print x
Traceback (most recent call last):
File "<pyshell#9>", line 1, in ?
print x
NameError: name 'x' is not defined
As you can see, x is not defined... it doesn't have ANY value. But if we
try CALLING the function, it'll print out x DURING the call:
>>> threeTimes(0)
x is now 0
0
Great... so x was 0 then. But what about now, AFTER we called it?
>>> print x
Traceback (most recent call last):
File "<pyshell#11>", line 1, in ?
print x
NameError: name 'x' is not defined
Okay... what's going on here is that 'x' took on a value TEMPORARILY,
while the function was being evaluated, but then it went back to being
undefined. Actually, a more precise definition would be that the
variable 'x' was "local" to the function, and so the 'x' that had been
set to 0 was destroyed when the function finished.
What will happen if we call threeTimes() with a bigger number? Let's
start with 1:
>>> threeTimes(1)
x is now 1
x is now 0
3
First, it starts up the function "threeTimes", which means that it has
to create an 'x' -- this gets set to 1 since that's what you used when
you called it. Then it prints it out, so you get the line "x is now 1".
It tries the 'if', and decides to go with the 'else' clause... so it
needs to return "3 + threeTimes(x-1)", or "3 + threeTimes(0)". But NOW
it has to work out what "threeTimes(0)" is.
So it starts up ANOTHER COPY of the function "threeTimes". The old copy
is still there (in which x=1), but the new copy has to set x=0. It
prints out x (so we get the line "x is now 0"), and then it tries the if
and finds out that all it has to do is return an answer of 0.
So the SECOND copy of "threeTimes" has finished, and the FIRST copy can
now continue. It now knows that "3 + threeTimes(0)" is just "3 + 0", and
so it returns "3", which then gets printed out.
I imagine you can now guess what happens when we call "threeTimes(6)"...
right?
>>> threeTimes(6)
x is now 6
x is now 5
x is now 4
x is now 3
x is now 2
x is now 1
x is now 0
18
There are many situations for which this technique (recursion) is very
powerful and useful, so it's worth learning even if it warps your brain
a little bit at first.
-- Michael Chermside
More information about the Python-list
mailing list