Global Python Keyword

In this lesson, you will learn the global keyword and variables and when to use them. Before reading this lesson, you are familiar with Python’s global, local, and nonlocal variables fundamentals.

What is the global term?

The global keyword in Python enables you to change a variable outside the current scope. It is used to construct a global variable and make local adjustments to the variable.

Global Keyword rules

The fundamental guidelines for Python’s global keyword are:

  • A variable is local when it is created inside a function.
  • A variable is, by default, considered global when defined outside a function. The usage of global keywords is not required.
  • The global keyword reads and writes global variables inside a function.
  • The global keyword has no impact when used outside of a function.

Employing a global keyword

Let’s understand using a function to access a global variable.

Example

var = 100  # global variable
def sum():
    print var

Output

100

However, there may be instances where changing the global variable from within a function is necessary. Let’s take another example of modifying a global variable inside the function.

Example

var = 100 # global variable
def sum():
    var=var+3;
    print(var)
sum()

Output

Traceback (most recent call last):
File "<string>", line 7, in <module>
File "<string>", line 4, in sum
UnboundLocalError: local variable 'var' referenced before assignment

We can only read from and write to the global variable within the function. The global keyword can be used as a fix for this error. Let’s take the same example of using global to change a variable inside a function.

Example

var = 100  # global variable

def sum():
    global var
    var = var + 3
    print var

sum()

Output

300

In the program above, inside the sum() function, we specify var as a global keyword.

The variable var is then increased by 3. Next, we invoke the sum() method. We end by printing the global variable var.