Benjamin
Benjamin

Reputation: 105

Confusion in an Python program related to topic of Namespace and Scope

I just stepped in python recently and now I reached to the topic of Namespace and Scope. With the intention of further understanding of this subject, I found this which contains a program resulting in my confusion.

And, here's the program:

1  def outer_function():
2      a = 20
3      def inner_function():
4          a = 30
5          print('a =',a)
6
7      inner_function()
8      print('a =',a)
10     
11 a = 10
12 outer_function()
13 print('a =',a)

And here's the result which you must be quite sure but I am not

a = 30
a = 20
a = 10

but the output in my mind should be

a = 30
a = 30
a = 20
a = 10

Even I modified the original code to be like this in order to make it clearer:

def outer_function():
    a = 20
    def inner_function():
        a = 30
        print('a1 =',a)

    inner_function()
    print('a2 =',a)
     
a = 10
outer_function()
print('a3 =',a)

But it still like this:

a1 = 30
a2 = 20
a3 = 10

So, the reason why I thought that there's supposed to a double a1 = 30 is because I believed that line5 in the code was executed twice as,

firstly, it runs when the outer_function() is called at line12 which goes from line1 to line8 and line5 is called with the a1 = 30 output

secondly, the line7 is called which triggered the line5 again with the same output as above,

finally the function outer_function() ends when line8 is done, that's when a2 = 20 show up.

Then go back to "main thread" (I just call it as this not actually mean it, or it is?) line13 and print a3 = 10

So, as what I got is not what I thought, what's wrong with my understanding of this program?

Thanks for spending time on reading my problem, it will be of great help to me if you can give me a hand on this :) Thanks in advance

Edit:

I just found out where my confusion was! Great appreciation to those who give me a hand. Turns out the main problem of my confusion is my unstable foundation of the programming knowledge. So, I incorrectly thought the line5 will run when the inner_function() was declared. Hahaha, how could this happen?? This so basic mistakes just happened -- the declaration of the function will never run until it is called in the program! That's why there's only one a = 30!

Anyway, I will keep in mind that do not make the same mistakes again. I'm appreciated to those who give a hand on this minor basic syntactic mistake!

Cheers!

Upvotes: 0

Views: 53

Answers (1)

chaiv
chaiv

Reputation: 184

The inner_function was declared on line 3, but it is only ever called once, and that's on line 7.

If you took out line 7, a1 would never print.

Upvotes: 2

Related Questions