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

(singke) #1

LISTING 12.8 Global Variables Causing Problems


Click here to view code image


#!/usr/bin/python3
width = 10
height = 60
total = 0
def area4():
total = width * height
print('Inside the function the total is:', total)
area4()
print('Outside the function the total is:', total)

The script1208.py code shown in Listing 12.8 defines three global variables: width,
height, and total. You can read them in the area4() function just fine, as shown by the output
of the print() statement. However, if you expect the total variable to still be set when the code
exits the area4() function, you have a problem, as shown here:


Click here to view code image


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

When you try to read the total variable in the main program, the value is set back to the global
value assignment, not the value that was changed inside the area4() function!


There is a solution to this problem. To tell Python that the function is trying to access a global
variable, you need to add the global keyword to define the variable:


global total

This equates the variable named total inside the function to the variable named total defined in
the main program. Listing 12.9 shows a corrected example of using this principle with the
script1209.py program.


LISTING 12.9 Properly Using Global Variables


Click here to view code image


#!/usr/bin/python3
width = 10
height = 60
total = 0
def area5():
global total
total = width * height
print('Inside the function the total is:', total)
Free download pdf