Unlocking the Secrets of Variable Scope in Python
Introduction to Variable Scope: Local and Global Variables
Welcome back! We are advancing swiftly to another significant terrain: the Variable Scope in Python. You've already learned how to create and call functions, as well as how to incorporate return statements. Now, we move to one of the crucial aspects of functions - understanding the scope of variables both within and outside of these functions. Are you thrilled to dive in? We guarantee it's going to be enlightening!
Understanding Local and Global Variables
In Python, a variable defined within a function has a scope confined to that function, making it a local variable. This simply means that you cannot access a local variable outside of the function in which it's declared.
What happens if we want a variable that is accessible across functions? That's where global variables come in! Global variables are those defined outside of any function and are accessible throughout your code — both inside and outside of functions.
Let's step through an example to illustrate:
Here, chosen_countries is a global variable. We are able to append a new country to our list within the function add_country(). After invoking add_country() with "Spain", we printed chosen_countries and found its value to be ["France", "Italy", "Spain"].
Trying to Access a Variable Not in Scope
Attempting to access a variable that is not within your current scope is a common mistake. This occurs when you try to access a local variable outside of the function in which it is defined.
Consider this example:
Running this code will result in a NameError because destination is not available in the global scope. Python enforces scope rules to maintain clarity and prevent unexpected alterations to data.
The Importance of Variable Scope
