Simple Function Question
David C. Ullrich
ullrich at math.okstate.edu
Wed Apr 26 14:57:23 EDT 2000
On Wed, 26 Apr 2000 11:44:10 -0700, "Akira Kiyomiya"
<akira.kiyomiya at autodesk.com> wrote:
>Hi, Could you explain this in dummy's language?
>
>This function prints out '4' and I have a feeling that x=1 and n=3, so
>add1(3) prints '4'.
>
>However, I have a difficlut time trying to see how these two arguments
>assigned to both x (especially x) and n.
Not sure exactly what the question is, but here's what
happens:
># Return a function that returns its argument incremented by 'n'
>def make_incrementer(n):
> def increment(x, n=n):
> return x+n
> return increment
>
>add1 = make_incrementer(1)
Think about what just happened when you said
make_incrementer(1). This actually executed the following
function definition:
def increment(x, n=1):
return x+n
The "n=1" means that n is an optional
parameter - if you don't include n then
it is set to 1; so calling increment(3)
is the same as saying increment(3, 1),
which should return 4.
If you'd said add2 = make_incrementer(2)
that would execute the definition
def increment(x, n=2):
return x+n
and set add2 to the function so defined - then
add2(x) is the same as add2(x,2).
>print add1(3) # This prints '4'
>
>
>
More information about the Python-list
mailing list