- Define "variable scope."
- Differentiate between a local variable and a global variable.
- Understand why variables defined inside a function cannot be accessed outside of it.
- Recognize that using parameters and return values is the best way to move data in and out of functions.
Where Do Variables Live?
As we start using functions more, you might wonder: what happens if I have variables with the same name in different places? Can a function see the variables I created outside of it? The answer to these questions is governed by a concept called variable scope.
A variable's "scope" is the part of the program where it is accessible. There are two main types of scope in Python.
Analogy: The Private House
Think of a function as a private house. The variables you create inside that house are local to it. People inside the house can see them, but anyone outside the house can't see in. The rest of your program, outside all the houses, is the "street," and variables created there are global.
Local Variables
A variable created inside a function is a local variable. It only exists while that function is running. As soon as the function finishes, the variable and its data are destroyed. You cannot access a local variable from outside its function.
Global Variables
A variable created outside of any function (at the top level of your script) is a global variable. It can be read from anywhere in your program, including from inside any function.
While functions can read global variables, it's generally considered bad practice. It can make your code confusing and hard to debug. The professional way to get data into a function is with parameters, and the best way to get it out is with return values.
Live Example: A Tale of Two Variables
The Trinket below is designed to demonstrate scope. It has a global variable and a function with its own local variable. Run the code and pay close attention to the output. You will see that it crashes with a NameError! This is on purpose. Follow the "Your Turn" instructions to understand why.
What happens in the function, stays in the function. Use parameters to pass data in and return to get data out.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.