Scope: where variables live

Functions, lesson 5 of 8

🧩 Functions, lesson 5 of 8

Scope: where variables live

Local vs global variables, UnboundLocalError, and why returning beats global.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Variables created inside a function (parameters included) are local: they exist only while that call runs, and the outside world can't see them. Variables created at the top level of your program are global.

Example

Local stays local

message disappeared when the function finished. Return values are how results get out.

Example

Reading a global

Functions can read globals. UPPER_CASE names are a convention for constants that never change.

Quiz

What does this print?

Because assigning inside a function creates a local variable, trying to update a global (count = count + 1) fails: Python treats count as local, but it has no value yet.

Example

UnboundLocalError

Python sees count = ... inside the function and treats count as local for the whole function, so reading it on the right-hand side fails.

Example

Two fixes

global lets a function reassign a global variable, but it makes code harder to follow and test. Prefer parameters and return values.

Example

Change vs. reassign

Step through the diagram below to see why one change sticks and the other doesn't.

Walkthrough

Parameters share the caller's objects

Globaldatanamelist102132str'old'
Step 1 of 5

Before the call: data refers to a list, name to the string 'old'.

shared with the caller
changed
after the call
Quiz

What does this print?

Exercise

Refactor away the global

Rewrite deposit without global: it should take (balance, amount) and return the new balance.

Then write withdraw(balance, amount) the same way. If amount is more than balance, return the balance unchanged.