A quick study of global, local and nonlocal Python variables

The letter “x” is created in the white space of 4 tall buildings
Photo by Rui Matayoshi on Unsplash

A Python variable is used to store a value (such as a string, an integer, a float, or a bunch of other types), and when the variable is created a space in memory is reserved. There is no need to declare what data type a variable is in Python — you can just create it and assign it. Let’s take a quick look at the three types of variables: global, local, and nonlocal.

A global variable is one that is declared outside of a function and can be accessed inside or outside of that function. For example:

And the result is:

The result
The result
The result of calling the global function inside and outside of the function

Now, what happens if I try to modify the global variable inside and outside of the function?

The result is:

Error message when a global variable is modified inside a function

So, the global variable can be modified while it is outside the function, but not when it is inside the function. For more, check out Eli Bendersky’s blog. As he explains, the UnboundLocalError happens:

…because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.

The second type of variable is a local variable. This variable is declared inside of a function and is only accessible to that function (while inside of the function). Here’s an example of a local variable called inside and outside of the function:

The result is:

Error message when a local variable is called outside the function

If I try to access the local variable outside the function, there is a NameError. Python tried to use the variable but doesn't see it defined.

Finally, the third type of variable is the keyword nonlocal. A nonlocal variable is used in nested functions where the local variable should not belong to the inner function. Here’s an example:

Nonlocal variable

For a result of:

Result of nonlocal variable

By using the keyword nonlocal, I was able to access the x=”nonlocal” outside of the inner function. This is a quick and dirty explanation to highlight the differences between the three types of variables.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store