Game Development Reference
In-Depth Information
we create a variable named spam inside of the function, the Python interpreter will
consider them to be two separate variables. That means we can change the value of spam
inside the function, and this will not change the spam variable that is outside of the
function. This is because these variables have different scopes, the global scope and the
local scope.
Global Scope and Local Scope
We have names for these scopes. The scope outside of all functions is called the global
scope . The scope inside of a function is called the local scope . The entire program has
only one global scope, and each function has a local scope of its own.
Variables defined in the global scope can be read outside and inside functions, but can
only be modified outside of all functions. Variables defined in a function's local scope can
only be read or modified inside that function.
Specifically, we can read the value of global variables from the local scope, but
attempting to change the value in a global variable from the local scope will leave the
global variable unchanged. What Python actually does is create a local variable with the
same name as the global variable. But Python will consider these to be two different
variables.
Look at this example to see what happens when you try to change a global variable from
inside a local scope. Remember that the code in the funky() function isn't run until the
funky() function is called. The comments explain what is going on:
# This block doesn't run until funky() is called:
def funky():
# We read the global variable's value:
print(spam) # 42
# We create a local variable named "spam"
# instead of changing the value of the global
# variable "spam":
spam = 99
# The name "spam" now refers to the local
# variable only for the rest of this
# function:
print(spam) # 99
# A global variable named "spam":
spam = 42
# Call the funky() function:
funky()
Search WWH ::




Custom Search