W
W
weranda2016-05-13 11:31:13
Python
weranda, 2016-05-13 11:31:13

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()

Seriously, I don't understand the logic. There is a variable a with value 1 . The function x calls the value of the global variable a . If you then try to shadow the global variable a , then an error occurs saying that I am trying to access a local variable before assigning a value to it. But I'm trying to first display the value of the global variable, and then shade the global variable.
I understand what the rule is, but is it logically correct?
Could you clarify the situation?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
newpy, 2016-05-13
@weranda

In the function x, the value of the global variable a is called.

did you come from javascript?
you have space in scopes in python.
you have inside the x() function,
because you write print(a) BEFORE you assign a value to it. The x() function does not know anything about the variable "a" which is equal to 1.
def x():
  # внутри функции ничего неизвестно о переменной а = 1 которая снаружи.
  # чтобы было известно надо использовать ключевое слово global, или передавать напрямую ваше    "а" = 1, в функцию x(a) 
  print(a) # ошибка тут. Выводите раньше чем присвоили значение.
  a = 2

a = 1
x()

To make it work
def x():
    global a
    print(a)
    a = 2
a = 1
x()

x() # prints 1
print(a) # prints 2

L
lega, 2016-05-13
@lega

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.

A
Anatoly Scherbakov, 2016-05-13
@Altaisoft

It works if you printenter before:
In my practice, I have never needed to do this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question