Lesson 30 of 4075%
(Progress persistence is disabled until Phase 9)
Python
Intermediate
Scope
Understand where variables can be accessed.
Scope
What You’ll Learn
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
def myfunc():
x = 300
print(x) # This works
myfunc()
# print(x) # THIS WILL CAUSE AN ERROR! x is not defined outside.
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
x = 300 # Global variable
def myfunc():
print(x) # Can access x from inside the function
myfunc()
print(x)
Shadowing
If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables.
x = 300
def myfunc():
x = 200 # Local x shadows the global x
print(x) # Prints 200
myfunc()
print(x) # Prints 300