Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Global and Local Variables in Python?
In Python, variables have different scopes that determine where they can be accessed. There are two main types: global variables (accessible throughout the entire program) and local variables (accessible only within the function where they are defined).
Local Variables
Local variables are created inside a function and can only be accessed within that function. They exist only during the function's execution ?
def my_function():
x = "Python" # Local variable
print("Inside function:", x)
my_function()
# print(x) # This would cause NameError
Inside function: Python
If you try to access a local variable outside its function, Python raises a NameError.
Global Variables
Global variables are defined outside functions and can be accessed from anywhere in the program ?
message = "Hello World" # Global variable
def display_message():
print("Inside function:", message)
display_message()
print("Outside function:", message)
Inside function: Hello World Outside function: Hello World
Modifying Global Variables
To modify a global variable inside a function, use the global keyword ?
counter = 10 # Global variable
def increment():
global counter
counter += 5
print("Inside function:", counter)
increment()
print("Outside function:", counter)
Inside function: 15 Outside function: 15
Local vs Global Variables Example
When both local and global variables have the same name, the local variable takes precedence inside the function ?
name = "Global" # Global variable
def test_scope():
name = "Local" # Local variable
print("Inside function:", name)
test_scope()
print("Outside function:", name)
Inside function: Local Outside function: Global
Comparison
| Aspect | Local Variables | Global Variables |
|---|---|---|
| Scope | Within function only | Entire program |
| Access | Limited to function | Anywhere in program |
| Memory | Created/destroyed with function | Exists throughout program |
| Modification | Direct assignment | Requires global keyword |
Conclusion
Local variables provide encapsulation and are preferred for function-specific data. Global variables should be used sparingly and with the global keyword when modification is needed inside functions.
