Let’s return to our puzzling example from the previous exercise:
def favorite_color(): color = 'Red' print(color)
Whenever we decide to call a function, a new local scope will be generated. Each subsequent function call will generate a new local scope. Since the local scope is the deepest level of the four scopes, names in a local scope cannot be accessed or modified by any code called in outer scopes. As a rule of thumb, any names created in a local namespace are usually also locally scoped.
In this case, the name of color
is scoped locally to the function favorite_color()
. Since the statement print(color)
is called outside of the function, it has no access to the local scope (and thus the local namespace) inside of favorite_color()
and returns an error.
However, if we were to refactor our code:
def favorite_color(): color = 'Red' print(color) favorite_color()
Then, we wouldn’t have trouble accessing the name of color
since now the print()
function is scoped locally, and our output would return 'Red'
.
Let’s take some time to practice the basics of local scope!
Instructions
Our close friend Jiho wants to start a painting business. In order to help, we have created a small painting application that will print out the required colors for a specific painting.
Take some time to examine the code provided, and run it to see an error come up! Why are we getting a NameError
?
Let’s fix the scoping error by moving the print
statement right above the for
loop defined in the painting()
function. This will put the function call in the correct local scope to be able to access painting_statement
.