Table of Contents
The scope of a variable or function is the region of code in which the variable or function is defined. It determines the accessibility of the variable or function to different parts of the program.
“`python
global_variable = 10
def my_function(): local_variable = 20
# Local variable is only accessible within the functionprint(local_variable) # Output: 20
def local_function(): local_function_variable = 30
# Local function variable is only accessible within the functionprint(local_function_variable) # Output: 30
def global_function(): global_function_variable = 40
# Global function variable is accessible from any part of the programprint(global_function_variable) # Output: 40
print(global_variable) # Output: 10
global_function() # Output: 40“`
The scope of a variable or function determines the accessibility of the variable or function within a program. Local variables and functions are accessible only within their scope, while global variables and functions can be accessed from any part of the program. Understanding scope rules is essential for writing well-structured and modular programs.
Categories