Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.2 (3 of 3): Scope: where a variable lives

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
ScopeThe part of a program where a variable can be used.inside one function
Global variableA variable made outside any function. The whole program can see it.the notice board
Local variableA variable made inside a function. Only that function can see it.your bag
FunctionA named piece of code that does one job.def double(x)
ParameterA name inside a function for a value that is passed in.price in def apply(price)
Return valueThe value a function gives back.return price - 2
VariableA name that holds a value.score

The cells students fill in are left blank in this preview.

Watch: where each variable lives

Press Play on the short film below. Watch the boxes: a variable made inside a function's box lives only in that box.

Film: scope, where a variable lives

Scope: where a variable lives

Every scene, as text

  1. A global variable is like the notice board in the hall: everybody can read it. A local variable is like your bag: only you can see inside.
  2. team = "Leeds" is made outside any function, so team is global. goals = 3 is made inside show_score, so goals is local. show_score() can use both and prints Leeds 3.
  3. A local variable lives only while its function runs. When show_score ends, goals disappears. print(team) still shows Leeds. print(goals) at the very end stops with a NameError.
  4. Each function has its own local variables. show_score cannot see points, and show_table cannot see goals. Both can read the global team.
  5. Two variables, one name. The global total holds 100. total = 5 + 5 inside add_up makes a new local total of 10. It prints Inside: 10, then Outside: 100.
  6. Myth (false): a function changes a global just by setting it. x = 9 inside change_x makes a new local x, so print(x) still shows 5. Only the line global x, shown in the lesson, would change it. Send values in with parameters and answers out with return.

Try it: global and local

Code: python
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.

Make a free account to save your work and track your progress.

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.

Scope as a picture

flowchart TD
  g[Global: team = Leeds. Everyone can see this]
  g --> f1[Function show_score. Local: goals = 3]
  g --> f2[Function show_table. Local: points = 12]
  f1 -. cannot see .- f2

Global or local?

Have a go

Global or local?

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

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

Code: python
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.

Make a free account to save your work and track your progress.

Worked example: follow the values

StepGlobal totalLocal total in add_upOutput
1 Global total is set100does not exist yet
2 add_up starts and sets its own total10010
3 print Inside10010Inside: 10
4 add_up ends100gone
5 print Outside100goneOutside: 100

The cells students fill in are left blank in this preview.

Send values in, send answers out

Tip

The best way to share data is to send it in as a parameter and send the answer out with return. Do not change a global variable from inside a function. It makes the program hard to follow.

Extra: Try it: the word global

Code: python
x = 5


def change_x():
    global x
    x = 9


change_x()
print(x)

# global x means: use the global x, do not make a new local one.
# So this prints 9. Take out the line global x and run it again.
# Now Python makes a new local x, so the global x stays 5 and it prints 5.
# Changing a global like this makes a program hard to follow. Send values in and out instead.

Make a free account to save your work and track your progress.

Match the word to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Your turn: use scope

The program has a global DISCOUNT and a global goals. Finish three functions. apply_discount subtracts DISCOUNT from a price. double_score uses a local variable called result. add_goal gives back a number one higher, and must not change the global goals. Press Run Tests.

Code: python
DISCOUNT = 2
goals = 0


def apply_discount(price):
    # Subtract the global DISCOUNT from the price.
    return None


def double_score(score):
    # Use a local variable called result. Give back double the score.
    # result must NOT exist outside the function.
    return None


def add_goal(current_goals):
    # Do not change the global goals. Give back the new number of goals.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Predict the output

Have a go

Predict the output

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Remember

Important

Global: made outside, seen everywhere. Local: made inside a function, seen only there. Send values in with parameters and send answers out with return.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.