Local and Global Scope
Local and Global Scope
Global Scope
When you initialize and use a variable outside of any function, it is said
to have global scope. Most of the variables you have created so far
have this global scope. In a simple program that has no functions at all,
every variable in that program is global. When a variable has global
scope, two important things are true:
In the example below, we declare and use two variables in the main
program - musicTypes and randomIndex. Because these variables
were first used outside of any function, they have global scope. The
variables are created when they are first initialized with an assignment
statement (=), and they will then last until your program ends.
:
Try It Now
Console Output...
You can run this example to verify that nothing surprising happens with
globally scoped variables. These variables behave the way you expect
based on your experience to this point. We have simply defined
"global" as a new term to describe these types of variables.
Local Scope
1. Local variables can only be seen and used from inside that
function
2. Local variables will be created when first assigned in the function
and destroyed as soon as the function returns
Let's re-work our music selection example to put most of the logic
inside a function. In the new code below, both musicTypes and
randomIndex are first used inside select_music(), and therefore have
local scope inside that function. Everything will work fine - until the
:
main code outside the function tries to access one of those variables.
Run the code and see what happens!
Try It Now
Console Output...
If you try to access a local variable from outside the function, you will
get a run-time error because that variable is not visible to any other
part of the program.
I like Jazz
Traceback (most recent call last):
File "code1.py", line 9, in
print(musicTypes) # ERROR - musicTypes does not exist at thi
NameError: name 'musicTypes' is not defined
Once you initialize a global variable, you can use it from anywhere in
your code, including inside a function. As you can see in the example
below, moving musicTypes out of the function to a global level still
works just fine. The statements inside select_music() can read
musicTypes as if it was declared locally.
:
import random
musicTypes = ["Rock","Rap","Country","Jazz","Pop"]
def select_music():
randomIndex = random.randrange(0,len(musicTypes))
return musicTypes[randomIndex]
Try It Now
Console Output...
Clearly, something strange is going on, as you can see in the example
output below.
I like Soul
Global musicTypes: ['Rock', 'Rap', 'Country', 'Jazz', 'Pop']
musicTypes = ["Rock","Rap","Country","Jazz","Pop"]
def select_music():
global musicTypes
musicTypes = ["Reggae","Disco","Techno","Hip Hop","Soul"]
Try It Now
:
Console Output...
Try It Now
Console Output...
Of course, this "best practice" rule is simply a guideline. You may find
situations in your own programs where using global data inside
functions is convenient. But the old saying, "Just because you can,
doesn't mean you should" is worth remembering when you make
design decisions.
Try to figure out how many print() statements will appear in the
output window and exactly what each print() statement will show.
Once you are confident of your answers, run the code to check the
actual results.
Try It Now
code1.py
:
Console
Console Output...
Did you predict the correct output? If you need help understanding
what happened, click on the "Show Solution" tab for a description of
each line.
: