Ticker

6/recent/ticker-posts

Variable Scope in Python

Variable Scope in Python

Introduction:
Variable scope in Python refers to the region of code where a variable can be accessed or referenced. Understanding variable scope is crucial for writing reliable and maintainable code.

Global Scope:
Variables defined outside of any function or class have a global scope. They can be accessed from any part of the code, including within functions.

Example:

python
global_var = 10

def print_global_var():
print("Global variable value:", global_var)

print_global_var()

Explanation:
In this example, global_var is defined outside the function and can be accessed within print_global_var() without any issues.

Local Scope:
Variables defined inside a function have a local scope, meaning they can only be accessed within that function.

Example:

python
def print_local_var():
local_var = 5
print("Local variable value:", local_var)

print_local_var()

Explanation:
The variable local_var is defined within the print_local_var() function and can only be used within that function.

Nested Scope:
In Python, when a function is defined inside another function, it creates a nested scope. Inner functions can access variables from outer functions but not vice versa.

Example:

python
def outer_function():
outer_var = "I'm from outer function."

def inner_function():
print(outer_var) # Accessing outer_var from the outer function

inner_function()

outer_function()

Explanation:
In this example
, inner_function() can access the variable outer_var from the outer function outer_function().

Global Keyword:
The global keyword can be used to modify a variable in the global scope from within a function.

Example:

python
global_var = 10

def modify_global_var():
global global_var
global_var = 20

modify_global_var()
print("Modified global variable value:", global_var)

Explanation:
By using the global keyword, the modify_global_var() function can modify the value of the global variable global_var.

Nonlocal Keyword:
The nonlocal keyword is used to modify a variable in the nearest enclosing scope that is not global.

Example:

python
def outer_function():
outer_var = "I'm from outer function."

def inner_function():
nonlocal outer_var
outer_var = "Modified value."

inner_function()
print("Modified outer variable value:", outer_var)

outer_function()

Explanation:
In this example, the nonlocal keyword allows the inner_function() to modify the variable outer_var in the outer function.

These are the key concepts related to variable scope in Python. Understanding them will help you write more robust and maintainable code.

Post a Comment

0 Comments