Local & Global Variables

Variables in Python can be classified as local or global based on their scope (where they can be accessed in the program). Understanding the differences between these types of variables is crucial for writing clean and effective Python code.


Global Variables

  • Global variables are variables declared outside of any function or class. They can be accessed and modified throughout the program, including inside functions.

  • Scope: Global variables are accessible from any part of the code after they are defined, including functions, loops, or conditionals.

  • Example:

    x = 10  # Global variable
    
    def print_global():
        print(x)  # Accessing global variable inside a function
    
    print_global()  # Output: 10
    
  • Modifying Global Variables: If you want to modify a global variable inside a function, you must use the global keyword.

    • Example:
      x = 10  # Global variable
      
      def modify_global():
          global x  # Indicating that we are referring to the global variable
          x = 20  # Modifying the global variable
      
      modify_global()
      print(x)  # Output: 20
      

Local Variables

  • Local variables are declared inside a function or a block of code. They are only accessible within the function where they are defined and cannot be accessed outside of it.

  • Scope: Local variables are only valid within the function or block they are created in. They are destroyed once the function finishes execution.

  • Example:

    def my_function():
        y = 5  # Local variable
        print(y)
    
    my_function()  # Output: 5
    # print(y)  # This would raise an error: NameError: name 'y' is not defined
    

Local vs Global Variable Precedence

If a local variable and a global variable share the same name, Python will prioritize the local variable when referencing the variable within a function. The global variable will only be used outside the function or if explicitly declared as global inside the function.

  • Example:
    x = 10  # Global variable
    
    def my_function():
        x = 20  # Local variable
        print(x)  # Output: 20
    
    my_function()
    
    print(x)  # Output: 10 (Global variable remains unchanged outside the function)
    

Using Global Variables Inside Functions

When working with global variables inside a function, you can either:

  1. Access the global variable (if no modification is needed).
  2. Modify the global variable (using the global keyword).
  • Example (Accessing):

    x = 50  # Global variable
    
    def print_value():
        print(x)  # Accessing global variable
    
    print_value()  # Output: 50
    
  • Example (Modifying):

    x = 50  # Global variable
    
    def modify_value():
        global x
        x = 100  # Modifying the global variable
    
    modify_value()
    print(x)  # Output: 100
    

Best Practices for Using Local and Global Variables

  1. Limit the Use of Global Variables:

    • It's generally a good practice to minimize the use of global variables because they can lead to hard-to-debug issues, especially when they are modified in multiple places in your code.
  2. Prefer Local Variables for Function Logic:

    • Use local variables for calculations and processing within functions. This keeps your code modular and reduces dependencies between functions.
  3. Use Global Variables for Constants:

    • Global variables can be useful for constants or configurations that need to be accessed across multiple functions or modules.
  4. Avoid Modifying Global Variables Unnecessarily:

    • Avoid modifying global variables inside functions unless necessary. This can lead to unexpected behavior, especially in large programs.
Task

Practice: Local & Global Variables

Objective: Understand the scope and behavior of local and global variables through practical examples.

  1. Global Variable Modification:

    • Create a program with a global variable call_count that keeps track of the number of times a function is called. Each time the function is executed, increment call_count and print its value.
    call_count = 0
    
    def count_calls():
        global call_count
        call_count += 1
        print(f"Function has been called {call_count} times.")
    
    count_calls()  # Output: Function has been called 1 times.
    count_calls()  # Output: Function has been called 2 times.
    
  2. Local Variable Experiment:

    • Create a function calculate_square() that takes a number as input, squares it using a local variable, and prints the result. Try to access the local variable outside the function and observe what happens.
    def calculate_square(num):
        square = num ** 2  # 'square' is a local variable
        print(f"Square of {num} is {square}")
    
    calculate_square(5)
    # print(square)  # This will raise an error because 'square' is local to the function
    
  3. Global and Local Variables with Same Name:

    • Define a global variable value = 10. Inside a function, define a local variable value = 20. Print both the global and local variables inside and outside the function to see how Python handles them.
    value = 10  # Global variable
    
    def local_value():
        value = 20  # Local variable
        print(f"Inside the function, local value: {value}")
    
    local_value()  # Output: Inside the function, local value: 20
    print(f"Outside the function, global value: {value}")  # Output: Outside the function, global value: 10
    
  4. Use Global Variable for Constants:

    • Write a program that defines a global constant PI = 3.14159 and uses it in a function to calculate the area of a circle. Ensure that the constant cannot be modified inside the function.
    PI = 3.14159  # Global constant
    
    def calculate_area(radius):
        area = PI * (radius ** 2)
        print(f"Area of the circle with radius {radius} is {area}")
    
    calculate_area(5)  # Output: Area of the circle with radius 5 is 78.53975
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth