What is global and local variables in Python?

A global variable is a variable that is defined and declared outside a function and must be used inside a function.

In Python, variables are used to store data in memory. Variables can be categorized as global variables and local variables based on their scope.

Global variables are those variables that can be accessed and modified from anywhere in the program, including inside functions. Global variables are defined outside of any function or class. If a variable is defined within a function, it will be treated as a local variable.

Local variables, on the other hand, are those variables that are defined inside a function or a block of code. These variables can only be accessed and modified within the function or block where they are defined. Local variables have a shorter lifespan and are destroyed when the function or block ends.

In Python, global variables can be accessed within a function using the global keyword. This allows us to modify the value of the global variable within the function.

Here's an example: 

 

global_var = 10

def func():
    local_var = 5
    global global_var
    global_var = global_var + local_var
    print(global_var)

func()
print(global_var)

In the above example, global_var is a global variable, and local_var is a local variable. The global keyword is used to access and modify the value of global_var inside the func() function. The output of this program will be: 

 

15
15

This is because the value of global_var is modified inside the func() function, and the updated value is printed both inside and outside the function.

Submit Your Programming Assignment Details