Stewdent.eu
▾

Variable Scope

Scope determines which parts of a program can see and use a variable. Understanding scope prevents confusing bugs and helps you write cleaner code.

Last updated: 16 November 2025

★★☆☆☆ Level 2computingprogrammingVariablesscope4 min read

Report an error

When you create a variable, it does not automatically become available everywhere in your program. The scope of a variable describes the region of code where that variable exists and can be used. Think of scope like a building with different rooms — a key that opens one room does not necessarily open all the others.

Global and Local Scope

There are two main types of scope you need to understand at this stage:

  • Global scope — a variable created outside any function. It can be read from almost anywhere in the program.
  • Local scope — a variable created inside a function. It only exists while that function is running, and is destroyed when the function finishes.
player_name = "Alex"        # global variable

def greet_player():
    message = "Welcome!"    # local variable
    print(player_name)      # OK — can read the global
    print(message)          # OK — local variable exists here

greet_player()
print(player_name)          # OK — still accessible globally
print(message)              # ERROR — message does not exist here
Note

In the example above, message only lives inside greet_player. Once the function finishes, Python discards the message variable entirely. Trying to use it outside the function causes a NameError.

Why Scope Matters

Scope keeps different parts of a program from accidentally interfering with each other. If every variable were global, a function deep in your code could silently overwrite a value used somewhere else — a nightmare to debug.

Consider this example:

score = 0               # global score

def calculate_bonus(points):
    score = points * 2  # this creates a NEW local variable
    return score

result = calculate_bonus(10)
print(result)   # 20
print(score)    # 0 — the global score is unchanged

The score inside calculate_bonus is a completely separate variable that shadows the global one temporarily. The global score is never touched.

Modifying a Global Variable Inside a Function

If you genuinely need a function to change a global variable, Python requires you to declare it with the global keyword:

high_score = 0

def update_high_score(new_score):
    global high_score
    if new_score > high_score:
        high_score = new_score

update_high_score(45)
print(high_score)   # 45
Warning

Using global should be done sparingly. Overusing it makes programs hard to follow because any function could change shared values at any time. Passing values as arguments and returning results is usually a cleaner design.

Scope in a Nutshell

Variable locationScope typeAccessible where?
Outside all functionsGlobalAnywhere in the file
Inside a functionLocalOnly inside that function
Function parameterLocalOnly inside that function

A Practical Example

def calculate_area(width, height):
    area = width * height   # local to this function
    return area

def calculate_perimeter(width, height):
    perimeter = 2 * (width + height)  # different local variable
    return perimeter

w = 5
h = 3
print(calculate_area(w, h))         # 15
print(calculate_perimeter(w, h))    # 16

Both functions have their own local variable. Neither can accidentally read or change the other's internal values, which makes both functions safe and independent.

Tip

When you get a NameError saying a variable is not defined, scope is one of the first things to check. Ask yourself: was the variable created inside a function you are now trying to use it outside of?

Practice Problems

A student writes x = 10 inside a function and then tries to print(x) outside the function. What will happen and why?

Show answer
Python will raise a NameError because x is a local variable that only exists inside the function. Once the function finishes running, x is removed from memory and is not accessible outside.

What is the difference between a global variable and a local variable? Give one advantage of using local variables.

Show answer
A global variable is defined outside all functions and can be accessed anywhere. A local variable is defined inside a function and only exists within that function. One advantage of local variables is that they cannot accidentally be changed by other parts of the program, which makes code safer and easier to debug.