What is scope (local, global)?

Scope Defined
Scope is like a container for variables. It places limits on how a variable/parameter can be accessed throughout the program. A single global scope is created whenever your program begins to run. Meanwhile, local scopes are created whenever a function is called. You can use the same name for different variables, provided they are in different scopes. For example, there can be two variables, one in local and the other in global scope, both named userAge.

Local Scope
Parameters and variables related to a called function exist in that function’s local scope. When the function returns a value, the local scope is destroyed and variables are forgotten (see example 2). Local variables can access global variables. However, local variables in any other local scope (ie. container) are not accessible.

Global Scope
Variables assigned outside a function exist in the global scope. When your program terminates, the global scope is destroyed and variables are forgotten. Global variables cannot access any local variables (see example 1).

#example 1 - the following produces an error
def myFunction():
     localVar = 123
print(localVar)
#output
Traceback (most recent call last):
 File "C:/Users/anran/Downloads/tbd.py", line 3, in <module>
 print(localVar)
NameError: name 'localVar' is not defined

#example 2
def myFunction():
     otherFunction()
     localVar=123
     print(localVar)
def otherFunction():
     localVar=321
myFunction()
#output
123

 

Advertisements