Hour 12. Creating Functions
What You’ll Learn in This Hour:
How to create your own functions
Retrieving data from functions
Passing data to functions
Using lists with functions
Using functions in your Python scripts
Often while writing Python scripts, you’ll find yourself using the same code in multiple locations.
With just a small code snippet, that’s usually not a big deal. However, rewriting large chunks of code
multiple times in your Python scripts can get tiring. Python helps you out by supporting user-defined
functions. You can encapsulate your Python code into a function and then use it as many times as you
want, anywhere in your script. This hour walks you through the process of creating your own Python
functions and demonstrates how to use them in other Python script applications.
Utilizing Python Functions in Your Programs
As you start writing more complex Python scripts, you’ll find yourself reusing parts of code that
perform specific tasks. Sometimes it’s something simple, such as displaying a text message and
retrieving an answer from the script users. Other times it’s a complicated calculation that’s used
multiple times in a script as part of a larger process.
In each of these situations, writing the same blocks of code over and over again in your script can get
tiresome. It would be nice to just write the block of code once and then be able to refer to that block
of code other places in your script, without having to rewrite it.
Python provides a feature that allows you to do just that. Functions are blocks of script code that you
assign names to, and then you can reuse them anywhere in your code. Any time you need to use that
block of code in your script, you simply use the name you assigned to the function; this is referred to
as calling the function. The following sections describe how to create and use functions in your
Python scripts.
Creating a Function
To create a function in Python, you use the def keyword followed by the name of the function, with
parentheses, as shown here:
def name():
Note the colon at the end of the statement. By now you should recognize that this means there’s more
code associated with the statement. You just place any code that you want in your function under the
function statement, indented, like this:
def myfunction():
statement1
statement2