Intermediate Python Knowledge

Variables and Scopes in Python — Global, Nonlocal, and Local

What’s the LEGB rule?

Yong Cui
The Startup
Published in
6 min readMay 12, 2020

--

Photo by Robson Hatsukami Morgan on Unsplash

No matter what Python projects you’re doing, you have to deal with variables. We should know that we can assign almost any data, including built-in lists, integers, tuples, custom classes, and functions, to the variables that we’re declaring. In this way, we can refer to and manipulate these data easily.

When you learn to deal with variables, have you ever seen the use of global keyword in some sample code? The following is a simplified example.

>>> # Declare a number 
>>> number = 1234
>>>
>>> # Create a function that can update the value
>>> def update_number():
... global number
... number = 5678
...
>>> # Check the current value, before vs. after the function call
>>> print(f'Before calling: {number}')
Before calling: 1234
>>> update_number()
>>> print(f'After calling: {number}')
After calling: 5678

Have you wondered why the global keyword is used here?

If you don’t know the answer, let’s learn it in this article. If you do, I hope that you can get a good refreshment and possibly learn some new knowledge because we’ll be talking about related topics, not only the global keyword.

--

--

Yong Cui
The Startup

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).