Python has two scopes for variables:
- Local scope: variables you create within a function are only available within the function.
- Global scope: variables you create outside of a function belong to the global scope and can be used everywhere.
In this lesson, I’ll show you the difference between the two scopes with examples.
Let’s start with the local scope. Take a look at the following code:
Above, we see the print message that ran from within the function. The second print fails because the variable “test_string” is local to the scope. It’s not available globally.
The variables you create globally can be used within a function. Here is the code:
Our function is able to print the contents of the global variable. There is a catch, however. The function can only read the global variable, it can’t modify it. There is an exception to this rule, which I’ll show you in a minute.
Overlapping Variable Names
What happens when you use the same variable name globally and within a function? Let’s find out:
The code above assigns the variable “test_string” globally and within a function. We receive an error message right away. Once you assign a variable within a function, Python sees it as a variable with local scope. We receive the error message because we try to print a variable that isn’t assigned yet within the function.
Let’s change our code a bit. Let’s assign the variable within the function before we try to print it:
This works. The variable has a different value, one for the global scope, and another for the local scope.
In the previous example, we noticed that you can read a global variable from within the function. You can’t create or modify a global variable though from within the function. There is an exception to this rule. It’s possible when you use the
Here is our code:
Above, I added the keyword
global to make “test_string” a global variable. After running the function, we print the variable. As you can see, the variable is available globally.
You have now learned how Python scopes work.
- Variables you create within a function have the local scope and are only available within the function.
- Variables you create outside of a function belong to the global scope.
- You can use the
globalparameter to make a variable in a function global.
I hope you enjoyed this lesson. If you have any questions feel free to leave a comment.