26. Variable Scopes in Python

Quiz: 0/5

In Python, variables can have different scopes, which determine where in the code they can be accessed. The primary scopes are global scope, local scope, and enclosing scope. Understanding these scopes is essential to managing variables effectively and avoiding bugs due to unintended changes.

Global scope

A variable has a global scope if it is defined outside of any function or block. These variables are accessible from anywhere in the code, including inside functions, unless a variable with the same name is redefined locally.

Example:

# Global variable
message = "Hello, World!"

def greet():
    print(message)  # Accessing the global variable

greet()  # Output: Hello, World!
print(message)  # Output: Hello, World!

Here, message is defined outside of any function, so it has a global scope. The greet() function can access it because it’s in the global scope.

Modifying global variables

To modify a global variable inside a function, you need to declare it as global. Without this, Python will create a new local variable instead of modifying the global one.

count = 10  # Global variable

def increment_count():
    global count
    count += 1

increment_count()
print(count)  # Output: 11

Using the global keyword allows increment_count() to modify the global variable count.

Local scope

A local scope refers to variables defined within a function. These variables can only be accessed within the function they are defined in and are not visible outside.

Example:

def greet():
    message = "Hello from the function!"  # Local variable
    print(message)

greet()  # Output: Hello from the function!

# Trying to access message outside the function raises an error
print(message)  # Error: NameError: name 'message' is not defined

In this case, message is local to the greet() function. It only exists during the function's execution and cannot be accessed outside of it.

Enclosing scope (nested functions)

When functions are nested inside other functions, the outer function's variables are in an enclosing scope. An inner function can access these variables but cannot modify them unless the nonlocal keyword is used.

Example:

def outer_function():
    outer_message = "Hello from the outer function!"

    def inner_function():
        print(outer_message)  # Accessing variable from the enclosing scope

    inner_function()

outer_function()
# Output: Hello from the outer function!

Here, outer_message is in the enclosing scope of outer_function(). The inner_function() can access it but cannot modify it directly.

Modifying enclosing scope variables with nonlocal

To modify a variable from an enclosing function inside an inner function, use the nonlocal keyword.

def outer_function():
    counter = 0

    def inner_function():
        nonlocal counter  # Modify the enclosing variable
        counter += 1
        print(counter)

    inner_function()  # Output: 1
    inner_function()  # Output: 2

outer_function()

Here, nonlocal counter allows inner_function() to modify counter, which is defined in the enclosing outer_function().

Summary

  • Global scope: Variables defined outside any function, accessible throughout the entire program.
  • Local scope: Variables defined within a function, accessible only inside that function.
  • Enclosing scope: Variables in an outer function are accessible to inner functions, but modifications require nonlocal.
  • Global keyword: Used to modify a global variable within a function.
  • Nonlocal keyword: Used to modify a variable in an enclosing (outer) function from an inner function.

Hands-On Practise

Exercise: Understanding variable scopes

Instructions:

  1. Global Scope: Create a variable x in the global scope and assign it a value of 5.
  2. Local Scope: Write a function local_scope_test() that defines a variable x locally and prints its value.
  3. Modifying Global Variable: Inside the function local_scope_test(), modify the global variable x by using the global keyword and set its value to 10.
  4. Nested Function and Enclosing Scope: Write a function outer() that defines a variable message in the outer function. Inside it, define a nested function inner() that prints the message variable.
  5. Nonlocal Keyword: Modify message inside inner() using the nonlocal keyword and change it to Modified Message.

Questions to think about:

  1. What happens to the global variable x after the function local_scope_test() is called?
  2. What does the nonlocal keyword do in the nested function?
Output:

Quizzes: 0/5

Question 1:

What is the global scope in Python?

  • Variables defined inside a function.
  • Variables defined outside of any function or block.
  • Variables only accessible within a loop.
  • Variables that exist during the execution of a function.

Question 2:

What does the global keyword do in Python?

  • It creates a new variable in the global scope.
  • It allows a function to modify a global variable.
  • It restricts access to a global variable inside a function.
  • It makes a local variable accessible globally.

Question 3:

What is the purpose of the nonlocal keyword in Python?

  • It makes a local variable accessible in the global scope.
  • It allows modifying a variable in an enclosing (outer) scope.
  • It prevents a variable from being modified in an enclosing scope.
  • It restricts the variable to be used only in the function scope.

Question 4:

What happens if you try to access a local variable outside of its function in Python?

  • It will print the value of the local variable.
  • It will raise a NameError.
  • It will automatically be promoted to a global variable.
  • It will be accessible in the global scope.

Question 5:

How does Python treat a variable defined inside a function with the same name as a global variable?

  • It creates a new global variable.
  • It modifies the global variable.
  • It creates a local variable, leaving the global variable unchanged.
  • It causes a NameError.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonUnderstanding *args and **kwargsNext lessonUnderstanding the global Keyword