Understanding Function Scope in Python: Global, Local, and Nonlocal Variables

A comprehensive guide on how variable scoping works in functions with real-world examples

Max N
2 min readMar 24, 2024

In this article, we will explore function scope in Python by discussing global, local, and nonlocal variables. We’ll cover what they are, when to use them, and demonstrate their usage through practical examples. By understanding these concepts, you can avoid common pitfalls related to variable scoping and improve your overall coding skills.

Global Variables

A global variable is defined outside of any function or class definition. These variables have a global scope, meaning they can be accessed from within any part of the program. Here’s an example demonstrating global variables:

# Define a global variable
counter = 0

def increment_counter():
# Access and modify the global counter
global counter
counter += 1

increment_counter()
print(counter) # Output: 1

To access and modify a global variable inside a function, it must first be declared as global. This informs Python not to create a new local variable but instead reference the existing global one.

Local Variables

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.