EXTREME NOOBIE

piet at cs.uu.nl piet at cs.uu.nl
Tue Aug 29 05:41:08 EDT 2000


>>>>> "skeetor" <skeetornospam at bellsouth.net> (S) writes:

S> Whats this i hear about a function?  I just downloaded  this Python thing,
S> and i am going through the online tutorials when I get to the "defining of a
S> function..."  The tutorial is real basic until that part (thats where it
S> starts assuming you know how to program, Doh!)

S> Just wondering  if some kind person can clearly and adequately explain this
S> defining of a function thing...

A function is a piece of program that does some work and that you can use
in other parts of your program. E.g. when you want to calculate some
formula a number of times, but each time with different parameters, you
make it into a function.

Your function has zero or more parameters which you have to give names,
that can be used inside the function definition. At every placve where you
use the function you have to supply values for the parameters.

Lets take an example: you want to calculate the sum of the squares of two
numbers. Let's call the function sumsquares. You can use any name for the
parameters (any valid identifier, let's call them a and b (Normally you
would use more descriptive names):

The function definition is:

def sumsquares(a, b):
        return a*a+b*b

return tells which value the function will produce. In this simple case the
function is just one statement, but in real life most functions will be
bigger and contain several statements.

Now let's use this function to calculate the sum of the squares of 3 and 4
and print the result:

print sumsquares(3, 4).

This will print 25

Of course you can do other things with the function value, e.g. assign it
to a variable or use it in another calculation, e.g.:

res = 2*sumsquares(5, 12)

Some function don't calculate a result, they just do something for you. In
that case return without any value can be used, or if it is the last
statement of the function, it can be omitted. To use such a function you
just use it as a statement.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list