Unit 3 • Lesson 5

Variable Scope and Lifetime

Overview

Understand the difference between local and global variables. You'll learn how Python determines where a variable is accessible, and why managing scope prevents naming conflicts and bugs, ensuring your code behaves predictably across different contexts.

Intermediate 20–25 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • Local vs global variables: Understand where variables can be accessed.
  • Variable scope: Learn how Python determines which variables are available.
  • Variable lifetime: Understand when variables are created and destroyed.
  • Best practices: Learn how to avoid common scope-related bugs.

Why This Matters

Understanding variable scope helps you write better code and avoid bugs. When you know where variables can be accessed, you can prevent naming conflicts, write more organized code, and understand why some variables work in some places but not others. This knowledge is essential for building larger programs.

Step 1: What Is Variable Scope?

Variable scope determines where in your code a variable can be accessed. Python has two main types of scope: local scope (inside functions) and global scope (outside functions). A variable's scope is like its "territory" - it can only be used within its own territory.

Local vs Global Variables
# Global variable (defined outside any function)
name = "Alice"

def greet():
    # Local variable (defined inside the function)
    message = "Hello"
    print(message + ", " + name)

greet()
# print(message)  # ERROR! message is local, can't access here
1

Global Variables

Variables defined outside any function are global. They can be accessed from anywhere in your program, including inside functions. In the example, name = "Alice" is a global variable because it's defined outside the function.

2

Local Variables

Variables defined inside a function are local. They can only be accessed within that function. In the example, message = "Hello" is a local variable because it's defined inside the greet() function.

3

Access Rules

Functions can read global variables, but if you try to access a local variable outside its function, you'll get an error. That's why print(message) outside the function would cause an error - message only exists inside greet().

Key Concept: Global variables are accessible everywhere, but local variables are only accessible inside the function where they're defined. This separation helps prevent bugs and keeps your code organized - each function has its own "workspace" with its own variables.

Mini Practice #1: Understanding Scope

Try It Yourself

Try running this code. Notice which variables are accessible where:

Press Run to see output

What happened? Inside the function, both global_var and local_var are accessible. The function can read the global variable, and it can use its own local variable. However, outside the function, only global_var is accessible. If you tried to print local_var outside the function (uncomment that line), Python would give you an error saying local_var is not defined. This is because local_var only exists inside the function - when the function finishes, the local variable is destroyed!

Step 2: Local Variables Are Isolated

Each function has its own separate set of local variables. Even if two functions use the same variable name, they're completely separate:

Separate Local Variables
def function1():
    x = 10
    print("Function 1, x =", x)

def function2():
    x = 20
    print("Function 2, x =", x)

function1()
function2()
print("Outside, x =", x)  # ERROR! x doesn't exist here

How It Works

Each function has its own "workspace" with its own variables. When function1() creates x = 10, that variable only exists inside function1(). When function2() creates x = 20, it's a completely different variable with the same name. They don't interfere with each other because they're in different scopes. Outside both functions, x doesn't exist at all - it was only created inside each function.

Mini Practice #2: Separate Scopes

Try It Yourself

Try running this code. Notice how each function has its own separate variables:

Press Run to see output

What happened? Both functions use variables named length and width, but they're completely separate! When calculate_area() runs, it uses length = 5 and width = 3 to calculate area = 15. When calculate_perimeter() runs, it uses its own length = 10 and width = 4 to calculate perimeter = 28. Even though they have the same names, they're different variables in different scopes. This isolation prevents functions from accidentally interfering with each other!

Step 3: Reading Global Variables

Functions can read global variables without any special syntax. You can use a global variable inside a function just like any other variable:

Reading Global Variables
count = 0  # Global variable

def increment():
    print("Current count:", count)  # Can read global

increment()
print("Final count:", count)

Remember: Functions can read global variables without any special keyword. Just use the variable name inside the function, and Python will look for it in the global scope if it's not found locally.

Step 4: Modifying Global Variables

If you want to modify a global variable inside a function, you need to use the global keyword. This tells Python "I want to use the global variable, not create a local one":

Modifying Global Variables
count = 0  # Global variable

def increment():
    global count  # Tell Python to use global count
    count = count + 1
    print("Count is now:", count)

increment()
increment()
print("Final count:", count)  # Output: 2
1

Declare Global

Use global variable_name at the start of your function to tell Python you want to modify the global variable, not create a local one.

2

Modify the Variable

Now you can modify the global variable. When you write count = count + 1, Python knows you mean the global count, not a local one.

When to Use Global

Generally, it's better to avoid modifying global variables. Instead, use parameters and return values to pass data between functions. However, sometimes you need to modify a global variable (like a counter or configuration), and that's when you use the global keyword.

Step 5: Variable Lifetime

Variable lifetime refers to when a variable is created and destroyed:

Global Variables

Created when the program starts and exist until the program ends.

name = "Alice"
# Created at program start
# Exists until program ends

Long lifetime

Local Variables

Created when the function is called and destroyed when the function ends.

def my_func():
    x = 10
    # Created when function called
    # Destroyed when function ends

Short lifetime

Key Concept: Local variables are temporary - they only exist while the function is running. Once the function finishes, all its local variables are destroyed. This is why you can't access them outside the function - they don't exist anymore!

End-of-Lesson Exercises

Exercise 1: Create Local and Global Variables

Create a global variable name with value "Python". Then create a function greet() that creates a local variable greeting with value "Hello" and prints both the greeting and name.

Use a global variable outside the function, and a local variable inside the function.

Write your code above and click "Check Answer" to verify it's correct.

Exercise 2: Modify a Global Variable

Create a global variable counter with value 0. Then create a function increment_counter() that uses the global keyword to increment the counter by 1 and prints it. Call the function twice.

Use global counter inside the function to modify the global variable.

Write your code above and click "Check Answer" to verify it's correct.