Python Functions
Python Variable Scope
Scope determines where in your code a variable can be seen and used. Python looks variables up using a clear order called the LEGB rule, and understanding it prevents a lot of confusing bugs.
Local Scope
A variable created inside a function is local to that function — it exists only while the function runs and is not visible outside it. Each function call gets its own fresh set of local variables.
def greet():
message = "Hello!" # local to greet()
print(message)
greet()
print(message) # NameError: message is not defined hereGlobal Scope
A variable created outside of any function, at the top level of your script, is global — it can be read from anywhere, including inside functions, without any special keyword.
site_name = "MyInternships" # global
def show_name():
print(site_name) # can read the global directly
show_name()The global Keyword
Reading a global variable inside a function works automatically, but modifying it requires the global keyword — otherwise Python assumes you are creating a brand new local variable with the same name.
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter) # 2Overusing global variables makes code harder to test and debug. Prefer passing values in as parameters and returning results instead, wherever practical.
The nonlocal Keyword
nonlocal is used inside a nested function to modify a variable that belongs to its enclosing (outer) function, without making it fully global. It is the key building block behind closures.
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
print(inner()) # 1
print(inner()) # 2
outer()The LEGB Rule
When Python looks up a name, it searches four scopes in this exact order and stops at the first match: Local, Enclosing, Global, Built-in.
| Letter | Scope | Meaning |
|---|---|---|
| L | Local | Inside the current function |
| E | Enclosing | Inside any outer (enclosing) function, for nested functions |
| G | Global | Top level of the module/script |
| B | Built-in | Python's built-in names, like print or len |
