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

(singke) #1

global variables in your Python scripts.


Local Variables


Local variables are variables that you create inside a function. Because you create the variables
inside the function, you can only access them inside the function. Outside the function, the rest of the
script code doesn’t recognize them. Listing 12.7 shows the script1207.py program, which
demonstrates this principle.


LISTING 12.7 Working with Local Variables in a Function


Click here to view code image


#!/usr/bin/python3

def area3(width, height):
total = width * height
print('Inside the area3() function, the value of width is:',width)
print('Inside the area3() function, the value of height is:',height)
return total
object1 = area3(10, 40)
print('Outside the function, the value of width is:', width)
print('Outside the function, the value of height is:', height)
print('The area is:', object1)

The script1207.py code defines the area3() function with two parameters and then uses those
parameters inside the function to calculate the area. However, if you try to access those variables
outside the function, you get an error message, like this:


Click here to view code image


pi@raspberrypi ~% python3 script1207.py
Inside the area3() function, the value of width is: 10
Inside the area3() function, the value of height is: 40
Traceback (most recent call last):
File "C:/Python33/script1207.py", line 11, in <module>
print('Outside the function, the value of width is:', width)
NameError: name 'width' is not defined
pi@raspberrypi ~%

The code starts out just fine, passing two arguments to the area3() function, which completes
without a problem. However, when the code tries to access the width variable outside the
area3() function, Python produces an error message, indicating that the width variable is not
defined.


Global Variables


Global variables are variables you can use anywhere in your program code, including inside
functions. Values assigned to a global variable in the main program are accessible in the function
code, but there’s a catch: While the function can read the global variables, by default it can’t change
them. Listing 12.8 shows the script1208.py program, which is an example of how this can go wrong
in your Python scripts.

Free download pdf