Fatskills
Practice. Master. Repeat.
Study Guide: Python Functions Scope of Variables Local vs Global global Keyword
Source: https://www.fatskills.com/python/chapter/python-functions-scope-of-variables-local-vs-global-global-keyword

Python Functions Scope of Variables Local vs Global global Keyword

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~5 min read

What This Is and Why It Matters

Understanding the scope of variables in Python is crucial for writing efficient and bug-free code. It determines where variables can be accessed and modified, affecting program behavior and performance. Misunderstanding scope can lead to unintended variable overwrites, making debugging difficult. For instance, accidentally modifying a global variable inside a function can cause unexpected results, leading to hard-to-trace bugs. Mastering this concept is essential for Python exams and professional coding.

Core Knowledge (What You Must Internalize)

  • Local Variables: Defined within a function and only accessible within that function. (Why this matters: Prevents unintended side effects.)
  • Global Variables: Defined outside functions and accessible throughout the program. (Why this matters: Useful for constants or shared data.)
  • global Keyword: Allows modification of global variables inside a function. (Why this matters: Necessary for updating global state from within functions.)
  • LEGB Rule: Local, Enclosing, Global, Built-in – the order Python uses to resolve variable names. (Why this matters: Understanding this order helps predict variable behavior.)
  • Enclosing Scope: Refers to variables in nested functions, accessible to inner functions but not global. (Why this matters: Important for closures and decorators.)

Step‑by‑Step Deep Dive

  1. Define a Local Variable
  2. Action: Create a variable inside a function.
  3. Principle: Local variables are confined to the function scope.
  4. Example:
    python
    def my_function():
    x = 10
    print(x)
    my_function() # Output: 10
  5. ⚠️ Pitfall: Trying to access x outside my_function will raise a NameError.

  6. Define a Global Variable

  7. Action: Create a variable outside any function.
  8. Principle: Global variables are accessible from any function.
  9. Example:
    python
    y = 20
    def my_function():
    print(y)
    my_function() # Output: 20
  10. ⚠️ Pitfall: Modifying y inside my_function without the global keyword will create a local y.

  11. Modify a Global Variable

  12. Action: Use the global keyword to change a global variable inside a function.
  13. Principle: The global keyword tells Python to use the global variable.
  14. Example:
    python
    z = 30
    def my_function():
    global z
    z = 40
    my_function()
    print(z) # Output: 40
  15. ⚠️ Pitfall: Forgetting the global keyword will create a local variable instead.

  16. Understand Enclosing Scope

  17. Action: Define a variable in a nested function.
  18. Principle: Enclosing scope variables are accessible to inner functions but not global.
  19. Example:
    python
    def outer_function():
    a = 50
    def inner_function():
    print(a)
    inner_function()
    outer_function() # Output: 50
  20. ⚠️ Pitfall: Trying to access a outside outer_function will raise a NameError.

  21. Apply the LEGB Rule

  22. Action: Resolve variable names using the LEGB rule.
  23. Principle: Python searches for variables in Local, Enclosing, Global, and Built-in scopes in that order.
  24. Example:
    python
    b = 60
    def outer_function():
    b = 70
    def inner_function():
    b = 80
    print(b)
    inner_function()
    outer_function() # Output: 80
  25. ⚠️ Pitfall: Misunderstanding the order can lead to unintended variable resolution.

How Experts Think About This Topic

Experts view variable scope as a hierarchy of accessibility. They mentally map out the LEGB rule to predict where a variable will be resolved. This hierarchical thinking allows them to quickly identify and fix scope-related issues, making their code more robust and maintainable.

Common Mistakes (Even Smart People Make)

  1. The mistake: Modifying a global variable inside a function without the global keyword.
  2. Why it's wrong: Creates a local variable instead, leaving the global variable unchanged.
  3. How to avoid: Always use the global keyword when modifying global variables inside functions.
  4. Exam trap: Questions that require global variable updates without the global keyword.

  5. The mistake: Accessing a local variable outside its function.

  6. Why it's wrong: Local variables are not accessible outside their defining function.
  7. How to avoid: Use return statements to pass local variables out of functions.
  8. Exam trap: Code snippets that attempt to access local variables outside their scope.

  9. The mistake: Confusing enclosing and global scopes.

  10. Why it's wrong: Enclosing variables are not accessible globally.
  11. How to avoid: Remember the LEGB rule and the hierarchy of scopes.
  12. Exam trap: Nested function scenarios that test understanding of enclosing scope.

  13. The mistake: Overusing global variables.

  14. Why it's wrong: Can lead to unintended side effects and make code harder to debug.
  15. How to avoid: Use global variables sparingly and prefer local variables or function parameters.
  16. Exam trap: Code examples that rely heavily on global variables for state management.

Practice with Real Scenarios

Scenario: You are writing a function to update a global counter.
Question: How do you modify the global counter inside the function? Solution: 1. Define the global counter outside the function.
2. Use the global keyword inside the function to modify the counter.
Answer:


counter = 0
def update_counter():
global counter
counter += 1 update_counter() print(counter) # Output: 1

Why it works: The global keyword allows the function to modify the global counter variable.

Scenario: You need to access a variable defined in an enclosing function.
Question: How do you access the enclosing variable inside a nested function? Solution: 1. Define the variable in the outer function.
2. Access the variable directly inside the nested function.
Answer:


def outer_function():
enclosing_var = 100
def inner_function():
print(enclosing_var)
inner_function() outer_function() # Output: 100

Why it works: The nested function has access to the enclosing variable due to the LEGB rule.

Scenario: You want to avoid modifying a global variable inside a function.
Question: How do you prevent accidental modification of a global variable? Solution: 1. Do not use the global keyword.
2. Use a local variable with the same name if needed.
Answer:


global_var = 200
def my_function():
global_var = 300 # This creates a local variable
print(global_var) my_function() # Output: 300 print(global_var) # Output: 200

Why it works: Without the global keyword, the function creates a local variable, leaving the global variable unchanged.

Quick Reference Card

  • Core rule: Use the global keyword to modify global variables inside functions.
  • Key principle: LEGB rule for variable resolution.
  • Critical facts:
  • Local variables are confined to their defining function.
  • Global variables are accessible throughout the program.
  • Enclosing variables are accessible to nested functions.
  • Dangerous pitfall: Modifying global variables without the global keyword.
  • Mnemonic: Remember LEGB – Local, Enclosing, Global, Built-in.

If You're Stuck (Exam or Real Life)

  • Check: The scope of the variable you are trying to access or modify.
  • Reason: From first principles by following the LEGB rule.
  • Estimate: The impact of modifying a global variable without the global keyword.
  • Find the answer: By reviewing the code for scope-related issues and using print statements to debug.

Related Topics

  • Closures: Understanding closures helps in managing enclosing scope variables effectively.
  • Decorators: Decorators often involve nested functions and enclosing scopes, making scope understanding crucial.


ADVERTISEMENT