I am trying to understand why python behaves this way in the code block below. I did my research, but could not find a good answer, so I came here to find out if someone can point me in the right direction or give a good explanation. I understand that this is due to some old ALGOL principle, but I do not quite understand this.
var = 5 def func1(): print(var) func1() def func2(): var = 8 print(var) func2() def func3(): print(var) var = 8 func3()
The result of this code is as follows:
5
8
UnboundLocalError: local variable 'var' referenced before assignment
I understand why we get outputs "5" and "8". But with "func3 ()" I was expecting to exit "5". It seems that the interpreter believes that I want to print the local "var" in the function instead of the global "var". Thus, this generates this error.
Or maybe if the variable is defined somewhere inside the function, then the function will use the local variable by default, not the global one with the same name.
But why exactly is python behaving like this? I'm not complaining, I'm just trying to figure something out ...
How can I use a predefined global variable in a function and then define a local variable with the same name inside the same function without changing the value of the global variable? (of course in python)
Thanks in advance to everyone. You are amazing people! :)
Edit_1: Thanks everyone for the great answers. I fully understand that it is a bad and impractical idea to use a predefined global variable in a function and then define a local variable with the same name inside the same function. I just thought about it from a theoretical point of view, because I saw it at a lecture in college. XD I can not find a single use case in which it would be optimal to do this!
Edit_2: I already read PEP8, and I know that being explicit is better than being implicit. :) That's true. Otherwise, the code will be confusing and lead to errors. This question was about some sort of useless and impractical college theory that I was trying to understand.
Edit_3: Now I fully understand why this is happening and what is happening here. Thanks to Randall Valenciano for providing this blog link which explains this very well.
What happens is that the function is interpreted as a whole, and not line by line. Therefore, when a function is interpreted, variable declarations of any defined variables move to the beginning of the function. Therefore, when we print "var", the function uses a locally declared variable that has not yet been assigned a value, and then the interpreter complains about it and throws it wrongly.
Thanks to all of you again! :) You really helped me! Now I finally understand what is happening there under the hood.