Understand and use local and global variables

Resources | Subject Notes | Computer Science

Local and Global Variables

In programming, variables are used to store data. Variables can be classified into two main types: local variables and global variables. Understanding the difference between these is crucial for writing well-structured and maintainable code.

Local Variables

A local variable is declared and exists only within a specific block of code, typically a function or a loop. It is not accessible from outside that block. Local variables help to keep code organized and prevent unintended side effects.

  • Scope: Limited to the block where they are defined.
  • Lifetime: Exist only while the block of code is being executed.
  • Example: Consider a function that calculates the area of a rectangle. A variable storing the width and height would be local to that function.

Example Code:


def calculate_area(width, height):
  area = width * height  # 'area' is a local variable
  return area

result = calculate_area(5, 10)
print(result) 

In this example, the variable area is local to the calculate_area function. It cannot be accessed directly from outside the function.

Global Variables

A global variable is declared outside of any function or block of code and can be accessed from any part of the program. Global variables are useful for storing data that needs to be shared across multiple functions.

  • Scope: Accessible from anywhere in the program.
  • Lifetime: Exist for the entire duration of the program's execution.
  • Caution: Excessive use of global variables can make code harder to understand and debug.

Example Code:


global_value = 10

def modify_global():
  global global_value
  global_value = 20

def print_global():
  print(global_value)

print_global()  # Output: 10
modify_global()
print_global()  # Output: 20

Here, global_value is a global variable. Both print_global and modify_global can access and modify its value.

Table: Local vs. Global Variables

Feature Local Variable Global Variable
Scope Limited to the block where defined Accessible from anywhere in the program
Lifetime Exists only during the execution of the block Exists for the entire duration of the program
Accessibility Not accessible outside the defining block Accessible from any part of the program
Use For temporary data within a function For data that needs to be shared across multiple functions

Summary

Choosing between local and global variables depends on the specific requirements of the program. Local variables promote code modularity and prevent naming conflicts, while global variables facilitate data sharing. It's important to use global variables judiciously to maintain code clarity and avoid potential issues.