Exploring the Local, Enclosing, and Global Scope
Here, you’re creating a local variable named
total with the value
0 inside of the function
print_total(). Inside the function body, you can access
total in your print call. Oh, and by the way, in line 3, you’re using a formatted string.
When you run the code, Python calls the function and prints
From function: total=0. So the variable
total exists in the local scope of
print_total(), but outside of
print_total(), the variable
total does not exist. If you do access the variable outside of the function—so for example, when you add a
print() function call here where you show the
total variable, or want to show the
total variable, and run the code—
The E in LEGB stands for enclosing. The enclosing scope is a special scope that only exists for nested functions. Names that you define in the enclosing scope are commonly known as nonlocal names. Okay, here I adjusted the
print_total() function from before to explore the enclosing scope. In Python, you can nest functions.
These nested functions are also called inner functions. In this example, I added an inner function named
inner_print_total() to the
print_total() function. I will not go into detail about inner functions, but I’ll give you a link to some Real Python resources if you want to learn more about them at the end of this course. When you run the file, you see that
0 both times, and there is no error although you don’t define the variable
total inside of
It means that it isn’t wrapped in a function, for example. To see the global value of
total, there’s also a
print() function in line 10 ,in addition to the
print() functions in lines 3 and 6. When you run the code, then you can see that the global variable
total can be accessed from everywhere. There are no errors, and all of our print outputs show the value
5 for the variable
05:18 Okay, so far we have L, E, and G of the LEGB acronym: the local scope, the enclosing scope, and the global scope. In the next lesson, we will tackle the fourth letter of LEGB and inspect the built-in scope.
Become a Member to join the conversation.