KAHIBARO Bookshelves
Discord Login Register

9.5. Scope (local vs global)

Understanding Scope in Python

In Python, scope determines where in your code a variable can be seen (accessed) and used. In this chapter, you’ll focus on two main kinds of scope:

  • Local scope
  • Global scope

You’ll also see how scope works with functions, and some common pitfalls to avoid.


Local Scope: Variables Inside Functions

A local variable is a variable that is created inside a function. It:

  • Exists only while the function is running.
  • Can be used only inside that function.
  • Disappears after the function finishes.

Example:

def greet():
    message = "Hello!"   # local variable
    print(message)
greet()
print(message)  # This will cause an error

Explanation:

  • message is created inside greet().
  • Inside greet(), print(message) works.
  • Outside the function, message does not exist, so print(message) causes a NameError.

You can think of a function as its own “room”; variables created in that room can’t be seen from outside.


Global Scope: Variables Outside Functions

A global variable is a variable that is created outside of all functions (at the top level of a file). It:

  • Can be accessed from any function in that file (read-only by default).
  • Exists for as long as the program is running.

Example:

message = "Hello from global scope!"  # global variable
def show_message():
    print(message)   # we can read the global variable
show_message()
print(message)

Here:

  • message is global because it’s defined outside any function.
  • show_message() can read and print the global message.
  • Code outside functions can also use message.

Local vs Global with the Same Name

If a variable with the same name exists both globally and locally, Python will use the local one inside the function.

Example:

x = 10   # global variable
def test():
    x = 5   # local variable
    print("Inside function:", x)
test()
print("Outside function:", x)

Output:

Inside function: 5
Outside function: 10
  • Inside test(), Python uses local x = 5.
  • Outside the function, Python uses global x = 10.

This is called variable shadowing: the local x shadows (hides) the global x inside the function.


Reading Global Variables Inside Functions

You can always read a global variable inside a function (as long as you don’t try to assign to a variable with the same name in that function).

Example:

price = 100
def show_price():
    # Only reading price, not assigning to it
    print("The price is", price)
show_price()

This works fine because the function is only reading price, not creating or changing a local variable with the same name.


Why Assignment Changes Things

If you assign to a variable name inside a function, Python treats that name as local to that function (unless you explicitly tell Python otherwise). That means you can’t both assign and read the global variable under the same name without extra steps.

Example that causes an error:

count = 0
def increase():
    print(count)   # trying to read count
    count = count + 1  # assigning to count (local)
increase()

This will cause an UnboundLocalError. Why?

  • Because count is assigned inside increase(), Python decides count is local in that function.
  • When Python reaches print(count), it looks for the local count first, but it hasn’t been assigned yet.
  • It does not use the global count, because the function has a local variable named count.

To fix this, you can:

  1. Use a different local variable name, or
  2. Pass count as a parameter and return a new value, or
  3. Use the global keyword (explained next).

The `global` Keyword (Changing Global Variables)

If you really need to change a global variable from inside a function, you can use the global keyword.

Syntax inside a function:

global variable_name

This tells Python:

“When I use variable_name in this function, I mean the global one, not a new local one.”

Example:

counter = 0   # global
def increase():
    global counter   # use the global counter, not a new local one
    counter = counter + 1
increase()
increase()
print(counter)   # 2

Now counter is updated globally.

When (and When Not) to Use `global`

Using global can make code harder to understand and debug, because many different parts of your program can change the same variable.

Better approaches:

  • Prefer parameters and return values to move data in and out of functions.
  • Use global only when you really need shared state (for example, a small script or a constant that won’t change).

Example without global:

def increase(value):
    return value + 1
counter = 0
counter = increase(counter)
counter = increase(counter)
print(counter)   # 2

This is clearer: increase does not depend on any global state.


The `nonlocal` Keyword (Mention Only)

In nested functions (a function defined inside another function), there is another keyword: nonlocal. It lets you change a variable from an outer function’s scope (not global, not local to the inner function).

You’ll rarely need this as a beginner, but here’s a tiny example so you recognize it:

def outer():
    x = 10
    def inner():
        nonlocal x
        x = x + 1
        print("Inside inner:", x)
    inner()
    print("Inside outer:", x)
outer()

Here, nonlocal x tells Python that x comes from outer(), not from inner() and not from the global scope.


The LEGB Rule (Where Python Looks for Variables)

When Python sees a variable name, it checks scopes in this order (LEGB):

  1. Local – inside the current function.
  2. Enclosing – in any outer functions (for nested functions).
  3. Global – at the top level of the file.
  4. Built-in – names that Python provides (like len, print).

It stops as soon as it finds the name.

Simple example (without nesting):

x = 100  # global
def demo():
    x = 5  # local
    print(x)
demo()        # prints 5 (local)
print(x)      # prints 100 (global)

Python:

  • Looks in the local scope inside demo() and finds x = 5.
  • Outside the function, it uses the global x = 100.

Scope and Function Parameters

Function parameters behave like local variables inside the function.

Example:

tax_rate = 0.2  # global
def calculate_price(price):  # price is a local variable
    total = price * (1 + tax_rate)  # total is also local
    return total
final = calculate_price(50)
print(final)
print(price)   # error: price is local to the function
  • price and total exist only inside calculate_price.
  • Outside the function, you cannot access price or total.

Common Scope Mistakes and How to Avoid Them

1. Expecting Local Variables to Be Global

Mistake:

def create_name():
    name = "Alice"
create_name()
print(name)  # error

Fix: return the value and assign it outside:

def create_name():
    return "Alice"
name = create_name()
print(name)

2. Overusing Global Variables

Mistake:

total = 0
def add_to_total(x):
    global total
    total += x
add_to_total(5)
add_to_total(10)
print(total)

This works, but logic is hidden and spread out.

Better: use return values:

def add(a, b):
    return a + b
total = 0
total = add(total, 5)
total = add(total, 10)
print(total)

3. Shadowing Global Names Without Realizing

Mistake:

data = [1, 2, 3]
def process():
    data = "not a list anymore"  # shadows global data
    print(data)
process()
print(data)  # still the original list, not changed

If you meant to change the global data, you must either:

  • Use global data inside the function (if really necessary), or
  • Return a new value and reassign it outside the function.

Practical Guidelines for Using Scope

  • Use local variables and parameters inside functions as much as possible.
  • Treat global variables mostly as constants (values that don’t change).
  • To move data:
    • Use parameters to bring data into a function.
    • Use return values to bring data out of a function.
  • Avoid naming local variables the same as global variables, unless you’re very sure of what you’re doing.
  • Remember: if you assign to a variable inside a function, Python treats it as local, unless you declare it global or nonlocal.

By understanding scope, you can write functions that are easier to read, test, and reuse, without unexpected side effects from variables changing in surprising places.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms