This week, Python 101 discusses how to abstract out parts of yourPython code into reusable functions, add flexibility to them by allowingthem to accept different arguments, and make them return specific values.Also included: a discussion of variable scope and functions to help youwrite your own functions. Confused? All is explained within...
Of course, defining a function is only half of the puzzle - for it to be of any use at all, you need to invoke it. In Python, as in Perl, PHP and a million other languages, this is accomplished by "calling" the function by its name, as I've done in the last line of the example above. Calling a user-defined function is identical to calling a built-in Python function like print() or type().
It should be noted that Python will barf if you attempt to call a function before it has been defined - look what happens when I try the following example:
#!/usr/bin/python
# main program begins here
print "Question: which is the greatest movie of all time?"
# call the function
greatMovie()
# ask another question
print "Question: which movie introduced the world to Luke Skywalker, Yoda
and Darth Vader?"
# call the function
greatMovie()
# define a function
def greatMovie():
'this prints the name of my favourite movie'
print "Star Wars"
Here's the output:
Question: which is the greatest movie of all time?
Traceback (innermost last):
File "./test.py", line 8, in ?
greatMovie()
NameError: greatMovie
Another important thing to remember about functions is that they're, at heart, objects...just like everything else in Python. Consequently, they can be assigned to other objects, passed as values or data structures, and otherwise treated as though they were any other Python object.
The following example demonstrates this object-oriented behaviour, by assigning one function to another, and then using the new assignment to invoke the function.
#!/usr/bin/python
# define a function
def greatMovie():
'this prints the name of my favourite movie'
print "Star Wars"
# assign function as an object
myFavouriteMovie = greatMovie
print "Question: which is the greatest movie of all time?"
# call function by its new name
myFavouriteMovie()
And the output is:
Question: which is the greatest movie of all time?
Star Wars