Python Docs
Python Scope — Full Detailed Notes
Scope defines where a variable is accessible. A variable can only be used inside the region where it is created.
What is Scope?
Understanding scope helps you control variable access and avoid conflicts between local and global names.
Local Scope
A variable inside a function exists only within that function.
def myfunc():
x = 300
print(x)
myfunc()Local Scope inside Inner Functions
Inner functions can access variables from their parent function.
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()Global Scope
A variable created outside any function belongs to the global scope and can be accessed anywhere.
x = 300
def myfunc():
print(x)
myfunc()
print(x)Same Variable Name (Local vs Global)
Local and global variables with the same name are treated separately.
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)The global Keyword
Use global to make a variable inside a function become global.
Create Global Variable
def myfunc():
global x
x = 300
myfunc()
print(x)Modify Global Variable
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)The nonlocal Keyword
nonlocal lets you modify variables from an enclosing (outer) function within a nested function.
def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x
print(myfunc1())The LEGB Rule
Python searches variables in the order:
- L – Local
- E – Enclosing
- G – Global
- B – Built-in
Example
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("Inner:", x)
inner()
print("Outer:", x)
outer()
print("Global:", x)Summary
Mastering scope prevents name conflicts and helps write clean, maintainable code.