Variable Scope and Nested Functions
In Python, where a variable is defined determines where it can be accessed — this concept is called scope.
Functions can also be nested, meaning one function is defined within another.
1. Local vs Global Scope
Variables defined inside a function are local — they only exist while the function is running.
Variables defined outside any function are global and can be accessed throughout the entire script.
message = "Hello from global scope" def show_message(): message = "Hello from local scope" print(message) show_message() print(message)
- Inside the function, a new
messagevariable is created. - The global variable remains unchanged.
2. Using global Keyword
To modify a global variable from inside a function, use the global keyword.
counter = 0 def increase(): global counter counter += 1 increase() print("Counter:", counter)
- Without
global, Python treatscounteras a new local variable. - With
global, it updates the variable outside the function.
3. Nested Functions
A function can be defined inside another — this is called a nested function. The inner function is local to the outer function and cannot be called directly from outside.
def outer(): print("Outer function") def inner(): print("Inner function") inner() outer()
inner()can only be called insideouter().- Nested functions help organize logic and encapsulate behavior.
Summary
| Concept | Description |
|---|---|
| Local Scope | Variables inside a function |
| Global Scope | Variables outside all functions |
global keyword | Allows modifying global variables inside functions |
| Nested Functions | Functions defined inside other functions |
What is the correct way to modify a global variable inside a function in Python?
Declare it as a local variable inside the function.
Use the local keyword before the variable.
Use the global keyword before the variable.
Define the variable inside the function.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result