Local variables

A local variable is declared inside a function or block and can only be accessed within that function or block. The lifetime of a local variable is as long as the function is executing. It gets destroyed once the function call is completed.

Global variables

A global variable is declared outside any function or block and can be accessed from any part of the program. The lifetime of a global variable spans the entire runtime of the program.

Defining local and global variables

Let’s define a global variable named global_variable using the global keyword. This is done outside the methods. We can access this variable from any part of the program, including within functions. To demonstrate this, let’s create a function named this_is_a_function. The global variable can be accessed both from within the function and outside it. If we create a simple variable called local_variable within this function, we’ll only be able to access it within the scope of this_is_a_function.

Press + to interact
global global_variable
global_variable = "Global"
def this_is_a_function():
local_variable = "Local"
print("Local variable =", local_variable)
print("Global variable =", global_variable)
this_is_a_function()
# print("Local variable =", local_variable)
print("Global variable =", global_variable)

Note: When we uncomment Line 11, we can see it results in an error due to the local scope of the variable.

Modifying variables

In this code, a global variable named global_variable is initially set to “Global”. A function is defined that creates a local variable with the same name (global_variable) and sets it to “Modified Global”. When the function is called, it prints the locally defined variable inside its scope, showing that local variables will take precedence over global ones with the same name within their respective scopes.

However, outside the function, the global variable retains its original value, i.e., “Global”.

Press + to interact
global global_variable
global_variable = "Global"
def this_is_a_function():
global_variable = "Modified Global"
print("This is inside the function")
print("Global variable = ", global_variable)
this_is_a_function()
print()
print("Outside the function = ")
print("Global variable = ", global_variable)

This demonstrates that changes made inside the function don’t affect the global scope. If we try to print the local variable outside the function, it would result in an error due to its limited scope within the function.