Tutorial - Python 3 basics Global and local variables

This tutorial is about Python functions, you will learn about keyword, default, variable-length argument and anonymous functions

We already had a short review about variables, but this was more about the basics and overall types of variables. In this tutorial, we'll cover global and local variables.

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

  • Global variables
  • Local variables

Global vs. Local variables:

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Example:

total = 5; # This is global variable.
def sum(arg1, arg2):
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total:", total)
   return total

# Now you can call sum function
sum(17, 19)
print ("Outside the function global total:",total)

When the above code is executed, it produces the following two results with global and local variables:

Inside the function local var: 36
Outside the function global var: 5

Here is an example when you declare a variable globally and you print it locally:

x = 10
def example():
    print(x)

example()

Here is the same example, but if we will try to modify x in our function, we will receive an error:

x = 10
def example():
    print(x)
    x += 5

example()

So there is a way how we can edit global variables locally. We need to use globally in function, example:

x = 10
def example():
    # what we do here is defined x as a global variable. 
    global x
    x += 5
    print(x)

example()
print(x)

Another way to change the global variable is to change the function to use and return argument:

x = 10
def example(x):
    x += 5
    return x

x = example(x)
print(x)

In this tutorial, we covered global and local variables and the basics of how to use them. It was simpler than you thought, wasn't it?