statement3
statement4
With Python, there’s no “end of function” type of delimiter statement. When you’re done with the
statements contained within the function, you just place the next code statement back on the left
margin.
Using Functions
To use a function in a Python script, you specify the function name on a line, just as you would any
other Python statement. Listing 12.1 shows the script1201.py program, which demonstrates how to
define and use a function in a sample Python script.
LISTING 12.1 Defining and Using Functions in a Script
Click here to view code image
#!/usr/bin/python3
def func1():
print('This is an example of a function')
count = 1
while(count <= 5):
func1()
count = count + 1
print('This is the end of the loop')
func1()
print('Now this is the end of the script')
The code in the script1201.py script defines a function called func1(), which prints out a
line to let you know it ran. The script then calls the func1() function from inside a while loop, so
the function runs five times. When the loop finishes, the code prints out a line, calls the function one
more time, and then prints out another line to indicate the end of the script.
When you run the script, you should see this output:
Click here to view code image
pi@raspberrypi ~ $ python3 script1201.py
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
This is an example of a function
Now this is the end of the script
pi@raspberrypi ~ $
The function definition doesn’t have to be the first thing in your Python script, but be careful. If you
attempt to use a function before it’s defined, you get an error message. Listing 12.2 shows an example
of this with the script1202.py program.
LISTING 12.2 Trying to Use a Function Before It’s Defined