w3resource

How do you access global variables inside a function? Is it possible to modify them?

Accessing and modifying global variables in Python functions

Inside a Python function, use the global keyword before the variable name to access global variables. This tells Python to refer to a global variable instead of a local variable. It allows you to access its value within the function. The global keyword also allows you to modify the value of a global variable within a function.

Example: Access and modify a global variable inside a function

global_var = 100  # Declare global variable

def access_global_variable_func():
    # Accessing the said global variable
    print("Global variable value:", global_var)

def modify_global_variable_func():
    # Indicate that we are using the global variable
    global global_var
    # Update the global variable
    global_var += 50  

access_global_variable_func() 
modify_global_variable_func()
print("Value of the updated global variable:", global_var)

Output:

Global variable value: 100
Value of the updated global variable: 150

In the example above, the "access_global_variable_func()" function simply accesses the global variable 'global_var' value and prints it. The "modify_global_variable_func()" function uses the "global" keyword before 'global_var', which allows it to modify the global variable by incrementing its value by 5.



Follow us on Facebook and Twitter for latest update.