Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 5 · Lesson 3 · Core

Local variables and scope

See which names a function can use, why local variables disappear and how to avoid a NameError.

  • 50 minutes
  • Serves O5
  • Assumes M5.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M5.L2: what does a function return if it has no return statement?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • say what a local variable is (Foundation);
  • predict a NameError (Core);
  • pass values in instead of relying on globals (Core).

Phase 2: Teach

Step 3 A familiar example

A clerk uses a scrap of paper to work out a sum, then throws it away. Only the answer is passed on. A local variable is the scrap of paper.

Step 4 Clear explanation

A variable made inside a function is local: it exists only while the function runs.

def tax_on(price):
    tax = price * 0.1
    return tax

print(tax_on(50))
print(tax)
5.0
NameError: name 'tax' is not defined
Outside: rate = 0.10Inside: tax (local)1After the call: tax is gone2Local names disappear when the function ends
Variables made inside a function are local: they exist only while the function runs.

The last line fails because tax belongs to the function and was thrown away when it finished. A name made outside any function is global and can be read inside one, but relying on it hides what a function needs. Better to pass the value in as a parameter, so the function can be understood and tested on its own.

Two functions can each have a local variable with the same name without clashing, which is why small functions are safe to combine. If a parameter has the same name as a global one, the local one is used inside the function.

Step 5 Worked example (4 marks)

For def f(x): y = x + 1; return y, then print(f(4)) and print(y), say what happens.

  1. f(4) sets y to 5 and returns 5. (1 mark)
  2. The first print shows 5. (1 mark)
  3. y was local, so the second print has no y. (1 mark)
  4. Answer: 5, then a NameError. (1 mark)

Go deeper: the professor's notes

Pass values in and return values out; do not rely on hidden names.
In

Parameters.

Out

return.

Local

Gone after.

Pass inparametersWorklocal namesReturnresultGonelocal names
Scope

Names

Where madeVisible where
inside a functiononly inside
outsideread anywhere

At work: A tax rate

A global rate changes by mistake.

  1. Pass the rate as a parameter.
  2. Test with a known rate.

What a careful practitioner decides. Parameters make a function predictable.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. A variable created inside a function is:

2. Using a local name after the function ends gives:

3. The clearest way to give a function a value is:

4. Two functions can use the same local name:

Phase 4: Close

Step 7 Recap

  • Local names exist only inside the call.
  • A NameError shows a name that is not visible.
  • Pass values in as parameters.

Step 8 Exit ticket (ungraded)

Explain why print(total) fails after def add(a, b): total = a + b.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Rewrite a function that uses a global tax rate so the rate is a parameter.

In industry: left-pad: eleven lines, thousands of users

On 22 March 2016 a developer removed a package called left-pad from the npm registry. Its final version was only 11 lines of code, yet npm said it had been fetched more than 2.4 million times in the previous month, and builds of well-known projects failed until it was restored.

Link to this lesson. A tiny function with a clear name and one job can become something many programs depend on.

Source: The Register, 23 March 2016; Wikipedia, npm left-pad incident

Common mistakes

MistakeWhy it fails
Expecting a local variable to surviveReturn the value you need.
Depending on a global that may changePass it in.
Reusing one name for different thingsUse clear separate names.

Limits. This lesson does not cover the global keyword, which is rarely the best choice.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What is the difference between print and return?
printshowsreturngivesNo returnNone
Print vs return

Print only shows text on the screen. Return gives the value to the program. A function that only prints gives back None.

Card 2 of 3 · What is a local variable?
MadeinsideLivesduring the callThengone
Local

A name created inside a function. It exists only while the function runs and is gone afterwards.

Card 3 of 3 · What is a NameError?
Causename not visibleFixreturn itOrpass it in
NameError

Python cannot see the name you used, for example a local variable used after the function has ended. Return the value you need instead.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards