Variables have a certain reach within a program. A global variable can be used anywhere in a program, but a local variable is known only in a certain area (function, loop)

Sometimes the word scope is used in projects: “its outside the scope of the project”, meaning not included. Likewise, a variable can be outside the scope of a function.

Related course: Complete Python Bootcamp: Go from zero to hero in Python


In the program below, balance is a global variable. It can be used anywhere in the code. But the variable x can only be used inside addAmount.

#!/usr/bin/env python3

balance = 0

def addAmount(x):
global balance
balance = balance + x


Visually that’s:


We have two variables: balance, a global variable that can be used anywhere. x, that can only be used inside the function (its not known outside, local scope).


Try the exercises below:

  1. Add a function reduce amount that changes the variable balance
  2. Create a function with a local variable

Download answers