Answer the question
In order to leave comments, you need to log in
What happens when a function is declared?
a = 1
def test():
....print a
....a = 2
Please help me figure out why during the execution of the first instruction of the function - "print a", it is already known that a local variable is defined further and accordingly " print a" will result in an error. Logically, during the declaration of a function, the interpreter does not simply skip the body of the function... What happens? :)
Answer the question
In order to leave comments, you need to log in
Roughly speaking, in python it is done in such a way that the same variable inside a function cannot be first global, then local. At the time of compilation, the interpreter "assumes" which variable will be represented as global and which local. At the moment the function is executed, the interpreter already knows which variable to look for in which namespace. A variable is either local or global. In my example, when the function is executed, having met the variable a (print a), the interpreter considers it already local, although not declared, and therefore says: "hey uncle, you don't want to set the value for the variable first." But if the global variable is only read in the function, then there are no problems. Presumably, this is done to optimize work with namespaces. Otherwise, one would have to do extra operations to find the necessary variable in different spaces. Thanks to all! :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question