Module 3 Lesson 5: Variable Scope
·Programming

Module 3 Lesson 5: Variable Scope

Understand where your variables live and die. Learn the difference between Global and Local scope to avoid accidental bugs.

Module 3 Lesson 5: Variable Scope

In Python, not all variables are accessible from everywhere. Some variables only exist inside a specific function, while others are available to the entire program. This concept is called Scope.

Lesson Overview

In this lesson, we will cover:

  • Local Scope: Variables that live inside a function.
  • Global Scope: Variables that live in the "open air."
  • The LEGB Rule: How Python looks for variables.
  • The global Keyword: Why you should use it sparingly.

1. Local Scope ("Inside the House")

A variable created inside a function is Local to that function. It is born when the function starts and dies when the function ends.

def my_function():
    x = 10 # Local Variable
    print(f"Inside the function, x is {x}")

my_function()
# print(x) # This will cause an ERROR! 'x' doesn't exist out here.

2. Global Scope ("On the Street")

A variable created in the main body of your Python file is Global. Any function can read it.

score = 100 # Global Variable

def show_score():
    print(f"The global score is {score}")

show_score() # Works perfectly

3. The Shadowing Problem

What happens if you have a local variable with the same name as a global one? The local one "shadows" (hides) the global one.

message = "Global Message"

def show_message():
    message = "Local Message" # This is a NEW local variable
    print(message)

show_message() # Prints "Local Message"
print(message)  # Prints "Global Message" (still safe!)

4. The global Keyword (Use with Caution)

If you want to change a global variable from inside a function, you must tell Python explicitly using the global keyword.

count = 0

def increment():
    global count # Tell Python we mean the global one
    count += 1

increment()
print(count) # Output: 1

Pro Tip: In professional coding, we try to avoid global variables whenever possible. It’s better to pass data in as Parameters and get data out as Return Values.


Practice Exercise: The Bank Balance

Create a file named bank_scope.py.

  1. Create a global variable balance = 500.
  2. Write a function deposit(amount) that adds to the global balance.
  3. Write a function withdraw(amount) that subtracts from the global balance.
  4. Write a function show_balance() that simply prints the current balance.
  5. Perform a few transactions and print the results.

Quick Knowledge Check

  1. What is a "Local Variable"?
  2. Can a function read a Global Variable without the global keyword?
  3. What happens to a local variable once the function finishes running?
  4. Why is using too many global variables considered a "bad practice"?

Key Takeaways

  • Variable scope determines where a variable can be seen or used.
  • Local variables are private to their functions.
  • Global variables are accessible everywhere.
  • Use global to modify global variables (but try to avoid it!).

What’s Next?

We understand the mechanics, but how do we build programs that are truly reusable? In Lesson 6, we’ll look at Writing Reusable Code and the best practices for structuring your functions!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn