What does a function do?

Steve Holden sholden at cox.rr.com
Tue Apr 24 01:09:48 EDT 2001


"alki" <webmaster at pawntastic.com> wrote ...
> So a function is just a group of codes? Then how do you use a function?
Will
> you please give me an example? Thanks
>
Suppose you wanted to say hello to several people. You could define a
function to say hello using a particular person's name. Such a function
could be defined as follows...

def sayhello(who):
    print "Hello,", who

If we then made the following calls:

sayhello("alki")
sayhello("steve")
sayhello("everybody")

then the program would print the following output, one line per function
call:

Hello, alki
Hello, steve
Hello. everybody

So, as D-Man said, it's first and foremost an abbreviation for code which
you want to use in several places (or even several programs). Of course, the
example above is a simple one, with one argument (who, the value that gets
passed through fro the call), and not much code in it. In fact it would be
quicker to just write the print statements!

However, functions can get very complex, taking multiple argumnents, making
decsisions and performing different processing based on the argument values,
and so on.

Does this help? Try writing a function of your own in the interactive
interpreter now! You'll need to enter a blank line after the end of the
definition, that's just the way the interpreter works interactively.

regards
 Steve





More information about the Python-list mailing list