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: Python Crash Course: Master Python Programming!

Example:

Introduction

Scope has to do with where a variable can be used. If you define a variable, it’s not necessarily usable everywhere in the code. A variable defined in a function is only known in a function, unless you return it.

def something():
localVar = 1

# this will crash because localVar is a local variable
print(localVar)

That means unless you return the variables from a function, they can only be used there. This is in stark constrast with global variables: global variables can be used anywhere including in multiple functions and the main code. Global variables are often defined at the top of the program.

Global and local variables

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

addAmount(5)
print(balance)

Visually that’s:

scope

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).

Exercise

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