← Back to Blog

Local vs global — where variables live

The problem...

You define a variable inside a function. You try to use it outside. Python says it doesn't exist.

Or you define a variable outside and try to change it inside a function. Nothing changes.

Variables behave differently depending on where they live.

The idea!

Every variable has a scope — the region of code where it exists. Variables defined inside a function are local — they live and die with the function. Variables defined outside are global — they exist for the entire script.

Local variables

def greet():
    message = "Hello, Bull."    # local variable
    print(message)

greet()
print(message)    # NameError — message doesn't exist here

message is created inside greet(). When the function ends — it's gone. Outside the function — it never existed.

Global variables

name = "Bull"    # global variable

def greet():
    print(f"Hello, {name}.")    # can read it

greet()    # Hello, Bull.

A function can read a global variable. It sees everything defined in the outer scope.

Local shadows global

name = "Bull"

def greet():
    name = "Horn"           # local — doesn't touch the global
    print(f"Hello, {name}.")

greet()         # Hello, Horn.
print(name)     # Bull — global unchanged

Defining a variable with the same name inside a function creates a local copy. The global stays untouched.

Why this matters

def calculate_bmi(weight, height):
    bmi = weight / height ** 2    # local — only exists here
    return bmi

result = calculate_bmi(70, 1.75)
print(bmi)       # NameError — bmi doesn't exist here
print(result)    # 22.857... — the returned value, not the local variable

The local variable bmi is gone after the function ends. But return sent its value out before that happened. That's why return matters.

Heads up!

  • Local variables — defined inside a function, gone when it ends
  • Global variables — defined outside, readable everywhere
  • Same name inside and outside — two different variables, no conflict
  • Functions can read globals — but modifying them requires global keyword (avoid this)

The mindset shift

Stop thinking: "Variables are everywhere."

Start thinking: "Every variable has a home. Know where it lives."

What you should understand now

  • Local scope — inside a function. Variable lives and dies with the function.
  • Global scope — outside all functions. Variable exists for the entire script.
  • Functions can read globals — but local variables shadow them
  • Use return to get values out of a function — don't rely on globals
[ login to bookmark ] // copied! 20 views · 2 min
// resources
Code Example scope.py
← prev RETURN Mini Project — BMI Calculator next → Return two things at once
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.