Variable scope
When you work with variables inside functions, it’s important to understand scope – the area of the program where a variable is visible/accessible. In Python, variables defined inside a function have local scope, while variables defined outside any function have global scope.
Local Variables: A variable assigned inside a function is local to that function. It exists only during that function’s execution and is not accessible outside of it. Each time you call the function, a new set of local variables is created for that call. For example:
def greet():
msg = "Hello from inside the function!"
print(msg)
greet()
print(msg) # This will cause a NameError
In the above code, msg is defined inside greet(). Printing msg inside the function works and will output "Hello from inside the function!". But when we try to print msg outside the function, we get a NameError: name 'msg' is not defined, because msg was a local variable and went away after greet() finished executing. Local variables cannot be directly accessed from outside their function.
Global Variables: A variable defined in the main body of the code (i.e., not in any function) is a global variable. Global variables have a scope that spans the entire file (and even beyond, if imported elsewhere): they can be read from inside functions, and from any code in the module/file. For example:
message = "Python is awesome!" # global variable
def display():
print("Inside function:", message)
display() # prints "Inside function: Python is awesome!"
print("Outside function:", message) # prints "Outside function: Python is awesome!"
Here, message is declared outside the function, so display() can access and print it, and it’s also accessible after the function call in the global context. Simply reading a global variable inside a function is fine. However, assigning to a variable inside a function will, by default, create a new local variable rather than affecting a global variable of the same name.
Local vs. Global with Same Name: If you have a global variable and a local variable with the same name, the local variable shadows the global one inside the function. The function will see only its local version, and the global variable remains unchanged. For instance:
x = 100 # global x
def f():
x = 42 # local x (shadows global x)
print("inside f, x =", x)
f()
print("global x =", x)
This will output inside f, x = 42 and then global x = 100. Inside f(), when we do x = 42, Python creates a new local variable x (this does not affect the global x). Thus, printing x inside gives 42, but outside, x is still 100.
Modifying Global Variables from Inside a Function: By default, you cannot assign to a global variable inside a function without explicitly telling Python that it’s global. If you try, Python will treat the assignment as creating a new local variable, which often isn’t what you intended and can lead to an error if you simultaneously try to read the global variable. Consider:
count = 10 # a global variable
def increment():
count = count + 1 # attempt to modify global count (ERROR!)
print("Inside function, count =", count)
increment()
This results in an UnboundLocalError complaining that the local variable count is referenced before assignment. The moment we assign count = count + 1 inside the function, Python assumes count is a new local variable in increment. It has no initial value (and we’re trying to use its current value on the right side of =, hence the error).
The global keyword: To modify a global variable inside a function, you must declare it as global in that function. Using the global keyword tells Python “don’t create a new local variable, use the existing global variable of this name.” For example:
total = 0 # global variable
def add_to_total(amount):
global total # declare that we mean the global 'total'
total = total + amount # now this will modify the global variable
print("Inside function, total =", total)
add_to_total(5) # Inside function, total = 5
print("Outside, total =", total) # Outside, total = 5
In this code, by declaring global total inside the function, the assignment total = total + amount updates the global variable total rather than creating a local one. After calling add_to_total(5), the global total has changed from 0 to 5. Use global carefully – it makes your function depend on external state. In many cases, it’s better practice to return values from functions and assign them to globals outside, rather than modifying globals directly.
Nonlocal variables: Python also has a nonlocal keyword for nested functions (when a function is defined inside another function) to modify variables in the outer (enclosing) function’s scope. This is a more advanced topic not needed for basic function use, but just be aware it exists for completeness.
Summary of Scope: By default, assignments inside a function create local variables. You can access global variables inside a function for reading, but to assign to a global variable from within a function, declare it with global. Local and global variables of the same name are different variables. Understanding scope helps prevent bugs – for example, accidentally using a global variable when you intended to use a local one (or vice versa). It’s often best to minimize reliance on global variables and instead pass needed values into functions and return results, which makes the functions easier to reuse and test.
