2 mins read

Scope

Definition:

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.

Variables:

  • Local variables: Variables declared within a function are local to that function and are only accessible within its scope.
  • Global variables: Variables declared outside a function are global variables and can be accessed from any part of the program.

Functions:

  • Local functions: Functions defined within a function are local to that function and are only accessible within its scope.
  • Global functions: Functions defined outside a function are global functions and can be accessed from any part of the program.

Scope Rules:

  • Encapsulation: Variables and functions within a class are scoped to that class.
  • Modules: Variables and functions in different modules are in separate scopes.
  • Global scope: Variables and functions declared outside any class or module are in the global scope and are accessible to all parts of the program.

Example:

“`python

Global variable

global_variable = 10

Local variable

def my_function(): local_variable = 20

# Local variable is only accessible within the functionprint(local_variable)  # Output: 20

Local function

def local_function(): local_function_variable = 30

# Local function variable is only accessible within the functionprint(local_function_variable)  # Output: 30

Global function

def global_function(): global_function_variable = 40

# Global function variable is accessible from any part of the programprint(global_function_variable)  # Output: 40

Accessing global variable

print(global_variable) # Output: 10

Accessing global function

global_function() # Output: 40“`

Conclusion:

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.

Disclaimer