Skip to content

Module 3 · Variables and Data Types — topic 15 of 15

Variable scope introduction

Scope decides where a variable can be seen. Get a first look at global and local scope, why variables inside a function are separate from those outside, and how Python finds a name.

Intermediate 12 min read·Lesson 43 of 306 in Python Programming

Learning objectives

  • Distinguish global and local variables
  • Predict which variable a name refers to
  • Avoid relying on changing global variables

Definition

Scope decides where a variable can be seen. Get a first look at global and local scope, why variables inside a function are separate from those outside, and how Python finds a name.

Introduction

A variable’s scope is the part of the program where its name can be used. Variables created at the top level of a file are global; variables created inside a function are local to that function and disappear when it finishes.

This lesson is an introduction. Module 9 covers scope in full alongside functions.

Why it matters

Scope lets functions use simple names such as total or count without clashing with the same names elsewhere. Understanding it explains surprising results, such as a function that seems to ignore a change you made outside it.

Detailed explanation

Global scope: names assigned at the top level of a module are visible everywhere in that file, including inside functions (for reading).

Local scope: names assigned inside a function exist only while that call runs. Each call gets fresh local variables.

If a function assigns to a name, that name is local to the function, even if a global with the same name exists. The global is untouched.

Python looks up names in order: Local, Enclosing function, Global, Built-in. This is called the LEGB rule.

To change a global variable from inside a function you would need the global keyword, but it is usually better to pass values in and return results out.

Syntax

Python
rate = 0.18 # global
def tax(amount):
result = amount * rate # result is local, rate is read from global
return result
  • Top-level names are global.
  • Names assigned inside the function are local.
  • Reading a global inside a function is fine; assigning to it creates a local instead.

Code examples

Reading a global inside a function

Python
rate = 0.18
def tax(amount):
return amount * rate
print(tax(1000))
Output
180.0

Local names vanish after the call

Python
def make_total():
total = 42
return total
print(make_total())
try:
print(total)
except NameError as err:
print("NameError:", err)
Output
42
NameError: name 'total' is not defined

More examples

Same name, different scopes

Python
count = 100 # global
def count_vowels(word):
count = 0 # local, separate from the global
for letter in word:
if letter in "aeiou":
count += 1
return count
print(count_vowels("education"))
print("global count is still", count)
Output
5
global count is still 100

Step-by-step explanation

  • The top-level count is a global set to 100.
  • Inside count_vowels, count = 0 creates a new local variable with the same name.
  • The loop increases only the local count, reaching 5 for e, u, a, i, o.
  • After the call, the global count is unchanged at 100.

Expected output

Running “Same name, different scopes” prints exactly:

TextOutput
5
global count is still 100

Practical applications

  • Large programs keep most data local to functions so parts don’t interfere with each other.
  • Constants such as TAX_RATE are often global, while working values stay local.
  • Bugs caused by changing globals from many places are a classic reason code is hard to maintain.

Best practices

  • Pass data into functions as arguments and return results.
  • Keep globals for constants that never change.
  • Avoid reusing global names for unrelated local variables.

Common mistakes

Updating a global without declaring it

Avoid

total = 0
def add(n):
total += n

Prefer

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

total += n makes total local, so reading it first raises UnboundLocalError. Pass and return values instead.

Expecting a local to exist outside

Avoid

def f():
x = 5
f()
print(x)

Prefer

def f():
return 5
x = f()
print(x)

Local names disappear when the function returns; return the value instead.

Key takeaways

  • Scope is where a name is visible.
  • Top-level names are global; names assigned in a function are local.
  • Python looks names up Local → Enclosing → Global → Built-in.

Try it yourself

  1. 1
    Write a function that uses a global DISCOUNT constant to compute a discounted price.
  2. 2
    Predict the output, then run it: x = 1; def f(): x = 2; return x; print(f(), x).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic