Back to Python
2026-01-305 min read

Python Variable Scope

Learn Python Variable Scope step by step with clear examples and exercises.

Title: Python Variable Scope - Understanding and Mastering Variables in Python

Why This Matters

In programming, variables are essential for storing data and values to be used throughout your code. However, understanding variable scope is crucial to avoid confusion and bugs in your programs. In Python, variable scope determines the visibility of a variable within different parts of your code. Mastering variable scope will help you write cleaner, more efficient, and bug-free code.

Prerequisites

Before diving into variable scope, make sure you have a solid understanding of:

  • Basic Python syntax (variables, operators, functions)
  • Control structures (if statements, loops)

Core Concept

In Python, variables can be classified as either local or global. The scope of a variable determines where it can be accessed within your code.

Local Variables

Local variables are created and exist only within the function or block of code they were defined. When a new function is called, any local variables inside that function are created anew with their default values (None for objects and 0, False, or None for numeric types).

def example_local():
x = 10
print(x)

example_local() # Output: 10
print(x) # NameError: name 'x' is not defined

In the example above, x is a local variable created within the example_local() function. When we call the function, it creates a new x with the value 10 and prints it. Once the function finishes executing, the local x variable is destroyed, causing an error when trying to access it outside of the function.

Global Variables

Global variables are variables that exist in the global scope, which means they can be accessed from any part of your code. To create a global variable, you simply assign a value to a name before defining a function or within the top-level script.

x = 10

def example_global():
print(x)

example_global() # Output: 10

In this example, x is a global variable that can be accessed from within the example_global() function. When we call the function, it prints the value of the global x.

Scope Rules

When a local and global variable share the same name, the local variable takes precedence over the global one within the local scope. To access or modify a global variable inside a function, you can use the global keyword.

x = 10

def example_global():
global x
x += 5
print(x)

example_global() # Output: 15
print(x) # Output: 15

In the example above, we have a global variable x. Inside the example_global() function, we use the global keyword to let Python know that we want to modify the global x instead of creating a new local one. After modifying the value of x, it is updated globally and can be accessed outside the function as well.

Block Scope (Python 3.7+)

In Python 3.7 and later, you can create variables with block scope using the nonlocal keyword. This allows you to access or modify variables in an enclosing function's local scope.

x = 10

def example_nonlocal():
def inner():
nonlocal x
x += 5
print(x)

inner() # Output: 15
print(x) # Output: 15

In the example above, we have a global variable x. Inside the example_nonlocal() function, we define an inner function called inner(). Within inner(), we use the nonlocal keyword to let Python know that we want to access or modify the enclosing function's local x. After modifying the value of x, it is updated within its local scope and can be accessed globally as well.

Worked Example

Let's create a simple program that demonstrates variable scope in Python:

def example_local():
x = 10
print(f"Local x: {x}")

def example_global():
global y
y = 20
print(f"Global y: {y}")

example_local()
print("Outside function: x not defined")

example_global()
print(f"Outside function: y: {y}")

In this example, we have two functions example_local() and example_global(). The first function creates a local variable x, while the second function creates a global variable y. When we run the code, it outputs:

Local x: 10
Outside function: x not defined
Global y: 20
Outside function: y: 20

Common Mistakes

  1. Forgetting to use global when modifying a global variable inside a function.
x = 10

def example_mistake():
x += 5 # NameError: name 'x' is not defined

example_mistake()
print(x) # Output: 10 (x was not modified because it was treated as a local variable)
  1. Accessing a non-existent local variable outside its function.
def example_mistake():
x = 10

print(x) # NameError: name 'x' is not defined (x was created as a local variable within the function and cannot be accessed outside it)
  1. Using the same name for both global and local variables, leading to unexpected behavior.
x = 10

def example_mistake():
x = 20 # Local variable shadows the global one
print(f"Local x: {x}")
print(f"Global x: {x}")

example_mistake() # Output: Local x: 20, Global x: 10 (local variable hides the global one within its scope)
print(f"Outside function: x: {x}") # Output: Outside function: x: 10 (global variable is still accessible outside the function)

Practice Questions

  1. Write a Python program that demonstrates using block scope with the nonlocal keyword.
  2. Given the following code, what will be the output when you run it?
x = 10

def example():
x = 20
print(f"Local x: {x}")
def inner():
nonlocal x
x += 5
print(f"Inner x: {x}")
inner()
print(f"Outer x: {x}")

example()
print(f"Global x: {x}")
  1. Explain what happens when you run the following code and why there is an error:
def example():
x = 10
print(x)

example() # Output: NameError: name 'x' is not defined

FAQ

--

  1. What happens when a local and global variable have the same name?

When a local and global variable share the same name, the local variable takes precedence over the global one within the local scope. To access or modify a global variable inside a function, you can use the global keyword.

  1. What is block scope in Python, and how does it work?

Block scope allows you to create variables that are only accessible within a specific block of code (a group of statements enclosed by indentation). To access or modify these variables from outside the block, you can use the nonlocal keyword.

  1. What is the difference between local and global variables in Python?

Local variables exist only within the function or block of code they were defined, while global variables can be accessed from any part of your code. When a new function is called, any local variables inside that function are created anew with their default values, whereas global variables maintain their values throughout the execution of the script.

Python Variable Scope | Python | XQA Learn