Understanding Scope: Python

Vittoria
3 min readJun 22, 2021

One of my first challenges when learning python was how to read the flow of the code. My mentor introduced me to the concept of each indent having their own “box” (local scope) and the first indents were part of the “main box” (global scope). Each box had the variables that were presented in each indentation and when the variable was called, it would search in its own box and if it was not found it would go to the main box, but if not seen in the main box then it will give an error. However, it does not go both ways. Here is a great youtube video explaining as well.

Below is an example where I will go through the entire scope of code using the above concept, but a little more advanced as there will be functions within functions.

In our “main box” we will have the following values:

Now when the print line in the code gets called, that is when the my_method scope is initiated and within that scope we have these values:

y = 22 because that is the value at which the my_method is being called at. You always want to start with that first value as now that changes what x is which is 22. Since y does not meet the requirements for the if statement, we continue to w which we do not know yet as we need to open another scope for that. See below.

z = 22 because it is being passed the value of x which is y which is 22. j = 12 and then again, when we hit x it opens up another new scope. Although we have already been in the my_method scope, we create an entire new one as it will create a chain reaction where each scope will disappear eventually as values are returned. Therefore, see below the second my_method scope.

y = 12 because my_method at j is 12 which then gets passed through to y and x = 12 because x = y. Since the if statement requirements are met, it will return y which is 12. Then that scope will disappear and we continue back up the chain to the my_second_method scope.

Therefore, x in my_second_method scope means it is 12 as that was the result of the my_method at j. Since it returns x which is 12, it will also disappear and we continue back up the chain to the first my_method scope.

w = 12 because that was the result of my_second_method at x in the first my_method scope. And now the first my_method will disappear. The result of the print statement will, therefore, be 12.

--

--

Vittoria
0 Followers

Join me in my journey as I learn softwares and languages. I am a fourth year student at Toronto Metropolitan University studying Business Technology Management.