Variable Scope in Python

Variable Scope in Python
Lesson 14. Variable Scope in Python

In Python, variable scope defines where in your code a variable can be accessed or modified. Think of scope as the visibility range of a variable — where it “lives” and where it can be seen.

  1. Local Variable

A local variable is one that is created inside a function and can only be used there. It exists temporarily — once the function finishes, the variable disappears.

def greet():
    message = "Hello, World!"  # local variable
    print(message)

greet()          # Output: Hello, World!
# print(message) # ❌ Error: 'message' is not defined

🧩 Explanation:

  • message is local to the greet() function.
  • Trying to use it outside the function causes an error because it doesn’t exist there.
  1. Global Variable:

A Global variable is defined outside any function, so it can be accessed anywhere in your program — both inside and outside functions.

Example:

name = "Alice"  # global variable

def show_name():
    print(name)

show_name()      # Output: Alice
print(name)      # Output: Alice

🧩 Explanation:

  • name is available everywhere in your code
  • Global variables exist as long as your program runs
  • If a variable name is the same locally and globally, the local version wins inside the function.

Local variables are like private notes inside a function, while global variables are public announcements everyone can read.

  1. Modifying Global Variables Inside a Function

Inside a function, you are not allowed to change a variable that was created outside of it, unless you use the special word global to get permission, (i.e., By default, Python does not allow you to modify a global variable from inside a function — unless you use the special keyword global)

count = 0  # global variable

def increase():
    global count
    count += 1

increase()
print(count)  # Output: 1

⚠️ Tip: Use global variables carefully — too many of them can make your code harder to debug.

  1. Nested Scope (Enclosing Scope)

You can define a function inside another function. When that happens, the inner function can access variables from the outer function — this is called enclosing scope. Think of it like a family in a house: A child in their bedroom can use their own toys (local scope), but they can also walk into the living room to use something that belongs to the whole family (enclosing scope). In the same way, an inner function can access variables from both its own scope and the outer function that contains it.

def outer():
    outer_var = "I am outside"
    
    def inner():
        print(outer_var)
    
    inner()

outer()  # Output: I am outside

🧩 Explanation:

  • The variable outer_var belongs to the outer function (outer()).
  • The inner function inner() can still access it — like a child borrowing something from the family living room.

A child (inner function) can play with their own toys (local variables) and also with shared toys in the living room (enclosing scope).

5 . Built-in Scope

Python has a built-in scope that contains reserved names like

  • len()
  • print()
  • int()
  • range()

These are always available unless you accidentally override them.

print(len("Hello"))  # Output: 5

Avoid using variable names that shadow built-ins.

len = 10  # ❌ Bad idea!
print(len("Hi"))  # Error: 'int' object is not callable

Try It Yourself

x = "global"

def outer():
    x = "enclosing"
    
    def inner():
        x = "local"
        print("Inner:", x)
    
    inner()
    print("Outer:", x)

outer()
print("Global:", x)

Output

Inner: local
Outer: enclosing
Global: global

Key Takeaways on Variable Scope

  • Local variables: Exist inside a function only.
  • Global variables: Exist outside any function.
  • Enclosing scope: Inner function accessing outer function variables.
  • Built-in scope: Reserved names and functions provided by Python.
  • Use global carefully if you need to modify global variables inside functions.