Scope refers to the region of a program where a variable is accessible.
A variable cannot be used everywhere — it is available only within a certain block or function, depending on where it is defined.
Local Scope :
A variable declared inside a function belongs to the local scope. It is accessible only inside that function.
Trying to access it outside function raises error
def greet(): message = "Hello" print(message) greet() #output Hello Global Scope :
A variable declared outside all functions is a global variable.
It is accessible:
inside functions
outside functions
throughout the program
language = "Python" def show(): print(language) show() print(language) #output Python Python Global Keyword :
By default, if you modify a global variable inside a function - Python treats it as local and throws an error.
To modify it — use the global keyword.
count = 0 def update(): global count count += 1 update() print(count) #output 1LEGB Rule :
| Scope Type | Where Defined | Accessible In |
|---|---|---|
| Local | inside function | that function only |
| Enclosed | outer function | inner function |
| Global | outside functions | entire program |
| Built-in | Python system | everywhere |