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.