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 Programming Course & Exercises
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.
1 | def something(): |
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.1
2
3
4
5
6
7
8
9
10#!/usr/bin/env python3
balance = 0
def addAmount(x):
global balance
balance = balance + x
addAmount(5)
print(balance)
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).
If you are a beginner, then I highly recommend this book.
Exercise
Try the exercises below:
- Add a function reduce amount that changes the variable balance
- Create a function with a local variable