[Tutor] functions

Kirby Urner urnerk@qwest.net
Mon, 28 Jan 2002 19:49:12 -0800


>
>Here is my question.
>
>
>OK.
>
>I don't know why I am having such trouble with this and I have a little
>perl and php experience, but i am having the roughest time figuring out
>functions. Basically my trouble arises in understanding how things get
>passed into and what the return statement returns.
>
>I hope I am being clear. can anyone offer some tips?
>
>
>TIA.

Just the basic function is like this:

    def f(x):
       return x*x

So f(3) returns 9 and like that.

If you want a default value for x, so the user needn't
give one, go:

    def f(x=3):
       return x*x

Now the user can go f() and get 9, or f(3) and get 9,
or f(5) and get 25.

Can you have several such variables, all with defaults?
Yes.

Can you have optional variables?  Yeah.  Define a
function like this:

     def f(*args):
        return args

   >>> f(10)
   (10,)
   >>> f(10,1,'a',12.3)
   (10, 1, 'a', 12.300000000000001)

Oh, so like all the parameters get lumped into a single
tuple named args.  And you can combine these:

     def f(x=3,*args):  etc.

Finally, a function can be set up to accept a dictionary:

   def f(x=3,*args1,**args2):
         return x*x, args1, args2

   >>> f(10,"the","talk",a=2,c=5,d=10)
   (100, ('the', 'talk'), {'a': 2, 'c': 5, 'd': 10})

"the" and "talk" go to *args1, while all the remaining
variable assignments get put into a single dictionary,
associated with **args2 (dictionary argument must come
after any others).

You can return anything.  You can even return another
function:

   >>> def f(x=3):
           def g(y):
              return y**x
           return g

   >>> h = f(2)
   >>> h
   <function g at 0x0113B040>
   >>> h(5)
   25

That's another aspect of functional programming -- the
ability to treat functions like variables, e.g. as
returned values, or as arguments to other functions.

There's a whole other discussion regarding arguments
passed from outside Python, or as part of an URL.

Perhaps you were asking in a cgi context, in which case
I was a little off target.  Also, when a module loads, it
executes, so you can have statements not inside a function
or class definition executing.  This is also important to
understand, when writing cgi scripts.

Kirby