Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
area5()
print('Outside the function the total is:', total)

Adding the one global statement causes the code to run correctly now, as shown here:


Click here to view code image


pi@raspberrypi ~$ python3 script1209.py
Inside the function the total is: 600
Outside the function the total is: 600
pi@raspberrypi ~$

Watch Out!: Using Global Variables
You may be tempted to use global variables to pass values to a function and retrieve
values from a function. While that certainly works, it’s somewhat frowned upon in
Python programming circles. The idea is to make a function as self-contained as
possible, so you can use it in other programs without lots of extraneous coding.
Requiring global variables for the function to work complicates reusing the function in
other programs. If you stick with parameters and return values, your functions can
easily be reused in any program where you need them!

Using Lists with Functions


When you pass values as arguments to functions, Python passes the actual value, and not the variable
location in memory; this is called passing by reference. However, there’s an exception to this.


If you pass a mutable object (such as a list or dictionary variable), the function can make changes to
the object itself. That may seem a bit odd, but it can come in handy.


Listing 12.10 shows the script1210.py script, which demonstrates passing a list to a function
that modifies the list.


LISTING 12.10 Passing a List Value to a Function


Click here to view code image


#!/usr/bin/python3
def modlist(x):
x.append('Jason')
mylist = ['Rich', 'Christine']
print('The list before the function call:', mylist)
modlist(mylist)
print('The list after the function call:', mylist)

The script1210.py code creates a function named modlist(), which appends a value to the
list passed as the function parameter.


The code then tests the modlist() function by creating a list called mylist, calling the
modlist() function, and displaying the value of the mylist list variable, as shown here:


Click here to view code image

Free download pdf