Python Variables :Global Variables

In Python, global variables are variables that are defined outside of any function or code block and can be accessed and modified from any part of the code, including within functions. However, there are some specific rules and behaviors when working with global variables inside functions.

1. Defining Global Variables

A global variable is defined outside of any function and is accessible across the entire program.

# Global variable
x = 10

def print_global():
    print(x)  # Accessing the global variable

print_global()  # Output: 10

2. Accessing Global Variables Inside Functions

You can access global variables from within a function without needing to declare them as global unless you want to modify them.

y = 5  # Global variable

def display():
    print(y)  # Accessing the global variable inside a function

display()  # Output: 5

3. Modifying Global Variables Inside Functions

To modify a global variable inside a function, you must explicitly declare it as global using the global keyword. Without this, Python will treat the variable as local to the function, creating a new local variable instead of modifying the global one.

Example:

x = 10  # Global variable

def modify_global():
    global x  # Declare the global variable so we can modify it
    x = 20    # Now we are modifying the global variable

modify_global()
print(x)  # Output: 20

If you don’t declare the variable as global, Python will treat it as a local variable, leading to an error if you try to modify it without first defining it locally.

z = 50  # Global variable

def modify_without_global():
    z = 100  # This creates a new local variable 'z'
    print(z)  # Output: 100 (local variable)

modify_without_global()
print(z)  # Output: 50 (global variable is unchanged)

4. Global Variables Across Multiple Functions

Global variables can be accessed and modified by multiple functions in your program, provided you declare them with the global keyword inside the functions where you need to modify them.

count = 0  # Global variable

def increment():
    global count
    count += 1

def decrement():
    global count
    count -= 1

increment()
print(count)  # Output: 1

decrement()
print(count)  # Output: 0

5. Local vs Global Variables

If a variable with the same name as a global variable is defined inside a function, Python will treat it as a local variable, and it won’t affect the global variable.

a = 10  # Global variable

def func():
    a = 5  # Local variable, shadows the global 'a'
    print(a)  # Output: 5 (local variable)

func()
print(a)  # Output: 10 (global variable)

6. Global Variables in Nested Functions

When dealing with nested functions, global variables can still be accessed by inner functions.

global_var = 100

def outer_function():
    def inner_function():
        print(global_var)  # Accessing global variable inside nested function
    inner_function()

outer_function()  # Output: 100

7. Using global with Mutable Data Types

If the global variable is a mutable data type like a list or dictionary, you don’t need the global keyword to modify the contents of the object (since you’re not reassigning the object itself).

my_list = [1, 2, 3]  # Global list

def modify_list():
    my_list.append(4)  # Modifying the contents of the global list

modify_list()
print(my_list)  # Output: [1, 2, 3, 4]

However, if you want to reassign the entire list to a new one, you need to use the global keyword.

my_list = [1, 2, 3]

def reassign_list():
    global my_list  # Declare 'my_list' as global to reassign it
    my_list = [10, 20, 30]

reassign_list()
print(my_list)  # Output: [10, 20, 30]

8. Best Practices with Global Variables

  • Minimize the use of global variables: Excessive use of global variables can make the code harder to debug and maintain. It’s generally better to pass variables as function arguments or use return values.
  • Use meaningful names: Ensure that global variables have meaningful and descriptive names to avoid conflicts and confusion with local variables.
  • Avoid modifying global variables unnecessarily: It’s a good practice to avoid modifying global variables inside functions unless it’s absolutely necessary. Passing arguments to functions or returning values from functions is often a better approach.

9. Global Variables with Modules

When using multiple modules, you can access and modify global variables across modules. You can import the module containing the global variable and reference it using module_name.variable_name.

Example:

If you have two modules, module1.py and module2.py, you can modify the global variables defined in module1.py from module2.py.

# module1.py
x = 10

# module2.py
import module1

print(module1.x)  # Output: 10
module1.x = 20
print(module1.x)  # Output: 20

In this way, you can share and modify global variables across modules.

Leave a Reply 0

Your email address will not be published. Required fields are marked *