Scope: where variables live

Functions, lesson 5 of 6

🧩 Functions, lesson 5 of 6

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.

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.