
Scope: Where Variables Live
As you start writing more complex Python programs, you'll encounter a concept called 'scope.' Scope dictates where in your code a particular variable is accessible. Think of it like a set of rules that determines visibility. Understanding scope is crucial for preventing unexpected errors and writing cleaner, more manageable code. Python has two primary types of scope: local and global.
A variable defined inside a function has local scope. This means it can only be accessed from within that specific function. Once the function finishes executing, the local variables are destroyed. This is a good thing because it prevents variables in one function from accidentally interfering with variables in another.
def greet():
message = "Hello from inside the function!"
print(message)
greet() # This works fine
# print(message) # This would cause a NameError!In the example above, message is a local variable to the greet() function. We can print it inside greet(), but trying to access it outside the function will result in a NameError because it no longer exists.
Variables defined outside of any function, at the top level of your script, have global scope. These variables can be accessed from anywhere in your program, both inside and outside of functions.
global_variable = "I am a global variable."
def display_global():
print(global_variable)
print(global_variable) # Accessible here
display_global() # Accessible inside the function