Answer the question
In order to leave comments, you need to log in
Why can't Python print the value of a global variable in a function before shadowing it?
Greetings
Question from the category of theoretical. I do not understand the logic of a simple function.
Available:
– global variable
– function
– local variable
Example:
def x():
print(a)
a = 2
a = 1
x()
Answer the question
In order to leave comments, you need to log in
In the function x, the value of the global variable a is called.
def x():
# внутри функции ничего неизвестно о переменной а = 1 которая снаружи.
# чтобы было известно надо использовать ключевое слово global, или передавать напрямую ваше "а" = 1, в функцию x(a)
print(a) # ошибка тут. Выводите раньше чем присвоили значение.
a = 2
a = 1
x()
def x():
global a
print(a)
a = 2
a = 1
x()
Because the variable exists at the start of the function, i.e. a local cell has already been selected under the name "a".
js works the same way.
Xs right or not, at least it's easier to implement, well, maybe it saves you from some implicit errors, for example, so as not to confuse global and local with the same name in the code.
It works if you print
enter before:
In my practice, I have never needed to do this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question