Skip to main content
z
Variable Scope
z
Variable Scope: Local and Global
 Scope refers to the visibility of objects. In other words which parts of
your application can see it or use it.
 Variables defined inside a function are local to that function. They are
hidden from the statements in other functions, which normally cannot
access them. When the function terminates the values are released.
 Question: What is another situation where the variable was only
known while the structure was executing?
 Because the variables defined in a function are hidden, other functions
may have separate, distinct variables with the same name.
 However, do not let this confuse you.
 Question: What does the above statement mean?
z
Local Variables
 A function’s local variables exist only while the
function is executing. This is known as the lifetime of
a local variable.
 When the function begins, its local variables and its
parameter variables are created in memory, and
when the function ends, the local variables and
parameter variables are destroyed.
 This means that any value stored in a local variable is
lost between function calls and posts.
z
Global Variables and Global Constants
 A global variable is any variable defined outside all
the functions in a program.
 The scope of a global variable is the portion of the
program from the variable definition to the end.
 This means that a global variable can be accessed by
all functions that are defined after the global variable
is defined.
Bad Programming: The use of global variables
Good Programming: Only creating global variables that
are constant, passing variables through functions
z
Updating a Global Variable
 Code:
 Updating a global variable:
 globVar = <val>
def functionName ():
global globVar
globVar = <new value>
Why: Without the keyword global inside the function referencing the
global variable, the function would just crate a local variable.
z
Scope Examples
z
Scope Examples