Scope
Scope determines where a variable is accessible. Python follows the LEGB rule: Local, Enclosing, Global, Built-in.
Local vs Global
A variable defined inside a function is local. A variable defined outside is global.
x = 10
def show():
x = 5
print("Inside:", x)
show()
print("Outside:", x)
Try it Yourself →
The global Keyword
Use global to modify a global variable from inside a function.
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter)
Try it Yourself →
Enclosing Scope (Closure)
Variables in an outer function are visible to an inner nested function.
def outer(msg):
def inner():
print(msg)
return inner
hello = outer("Hello!")
hello()
Try it Yourself →