Vinay Garg Assistant Professor

Lesson 23: Scope of variables: local and global

Where a variable is created decides where it can be seen. A local variable lives inside its function; a global one lives for the whole program. Mixing them up produces the confusing UnboundLocalError.

A dark code window showing a local variable inside a function and a global one outside

In short

  • A local variable is created inside a function and disappears when the function ends.
  • A global variable is created at the top level of the file and can be read anywhere.
  • Assigning to a name inside a function makes it local unless you declare `global name` first.
  • `global` works, but returning a value is usually the cleaner way to change shared state.

2

scopes in this lesson: local and global

Python docs

0

ways a function can change a global without the keyword

Python docs

The two scopes you will meet first

Scope is the part of a program where a name can be used. Two matter from the start:

  • Local: a name created inside a function. It exists only while that function runs.
  • Global: a name created at the top level of the file. It exists for the whole run.

The program

# scope.py — the same name in two places

count = 10              # global

def show():
    count = 5           # local: a different variable
    print("inside:", count)

def change():
    global count        # use the global one
    count += 1

def read_only():
    print("read from inside:", count)

show()
print("outside:", count)     # unchanged
read_only()                  # globals can be read without any keyword
change()
print("after change:", count)

How it works, step by step

  1. count = 10 creates a global.
  2. Inside show(), count = 5 creates a new local name. The global is untouched.
  3. When show() returns, its local count is gone. Printing the global still gives 10.
  4. read_only() only reads count, so Python looks outside the function and finds the global. Reading never needs a keyword.
  5. change() declares global count, so count += 1 edits the global and it becomes 11.

What it prints

inside: 5
outside: 10
read from inside: 10
after change: 11

The error that catches everyone

total = 0

def add(mark):
    total = total + mark     # UnboundLocalError

add(10)

Python sees an assignment to total inside the function, so it treats the name as local for the whole function. The right-hand side then reads a local that has not been given a value yet. Two honest fixes: pass the value in and return the new total, or declare global total before using it.

Why returning is usually better

total = 100

def add(total, mark):
    return total + mark

total = add(total, 10)
print(total)     # 110

The dependency is written down in the function signature, the function can be tested with any input, and nothing else in the program can change the value behind your back.

Common mistakes

  • Reading a local variable outside the function that created it: NameError.
  • Adding global to every function to avoid thinking about data flow. It works, and it makes bugs travel.
  • Assuming two functions with the same local name share a value. Each call creates its own.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Program 14: demonstrate local and global scope with one variable of each and print both.
  2. Write a function that reads a global counter and returns it, then another that changes it with `global`.
  3. Show what happens when a function assigns to a name that also exists globally, and explain the result in a comment.

Sources

Frequently asked questions

What is the difference between local and global variables?

A local variable is created inside a function and exists only while it runs. A global variable is created at the top level of the file and can be read anywhere in it.

How do I change a global variable inside a function?

Declare it first with global count, then assign. Without the declaration, an assignment creates a new local name instead of changing the global.

Why do I get UnboundLocalError?

Because the function assigns to a name that is also global, so Python treats it as local throughout. Reading it before that assignment fails. Use a parameter and return, or declare global explicitly.

Is using global good practice?

Rarely. A function that changes a global is hard to test and easy to break from a distance. Passing a value in and returning the new one keeps the flow visible.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.