The notice board and your bag
At college there is a big notice board in the hall. Everybody can read it.
You also have a bag. Only you can see inside it.
Variables (names that hold values) work the same way. Some can be seen by the whole program. Some can only be seen inside one small part.
Key words
| Word | What it means | Example |
|---|---|---|
| Scope | The part of a program where a variable can be used. | inside one function |
| Global variable | A variable made outside any function. The whole program can see it. | the notice board |
| Local variable | A variable made inside a function. Only that function can see it. | your bag |
| Function | A named piece of code that does one job. | def double(x) |
| Parameter | A name inside a function for a value that is passed in. | price in def apply(price) |
| Return value | The value a function gives back. | return price - 2 |
| Variable | A name that holds a value. | score |
The cells students fill in are left blank in this preview.
Try it: global and local
team = "Leeds"
def show_score():
goals = 3
print(team, goals)
show_score()
print(team)
# team is global: it works everywhere.
# goals is local: try print(goals) at the very end.
# Python will say: NameError.
What is scope?
Scope means the part of a program where a name can be used.
A global variable is made outside any function. Every function can read it. A local variable is made inside a function. It lives only while that function runs, then it disappears.
Global or local?
Have a go
Global or local?
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Why have scope?
Imagine 20 programmers, each with a variable called total. If every total were global, they would change each other's values.
Local variables keep a function's work private. A function cannot break a variable it does not own. This also makes bugs easier to find.
Try it: two variables with one name
total = 100
def add_up():
total = 5 + 5
print("Inside:", total)
add_up()
print("Outside:", total)
# There are two different variables called total.
# One is local. One is global. The local one does not change the global one.
Worked example: follow the values
| Step | Global total | Local total in add_up | Output |
|---|---|---|---|
| 1 Global total is set | 100 | does not exist yet | |
| 2 add_up starts and sets its own total | 100 | 10 | |
| 3 print Inside | 100 | 10 | Inside: 10 |
| 4 add_up ends | 100 | gone | |
| 5 print Outside | 100 | gone | Outside: 100 |
The cells students fill in are left blank in this preview.