开发者

Can a variable be used inside a function without a Global declaration inside that function

CODE 1:

x=4    
def func():
          print("HELLO WORLD")
          y=x+2
          print (y)
          print (x) # gives o/p as HELLO WORLD 6,4,4.

func()    
print (x)

CODE 2:

x=4    
def func():

          print("HELLO WORLD")
          y=x+2
          x=x+2 # gives an error here
          print (y)
          print (x) 

func()
print (x)
开发者_运维知识库

In the first code, it is not showing any error, it's adding the x value to 2 and resulting back to y and it prints the o/p as 6,4,4. But Actually as I learnt so for, it should point an error because I am not giving the global declaration for x variable inside the func(). But its not ponting any error but in Code 2 it gives an error saying that x referenced before assignment.

The question is can x can be used for the assignment of its value to other variables? Even it is not followed with global declaration?


You can read global variables without explicitly declaring them as global (Code 1)

But you are not allowed to assign to a global variable without explicitely declaring it as global. (Code 2)

This is because there is no harm in reading, but when assigning you might get unexpected behaviour (especially if it's a long code with many variables and you think it's a unique name you are using, but it's not).


In the first function you haven't assigned to x, so the compiler doesn't treat it as a local variable. The runtime will automatically get x from the containing scope. You can easily inspect that x is not considered a local variable:

>>> func1.__code__.co_varnames
('y',)

In the 2nd function you're assigning to x, so the compiler treats it as a local variable:

>>> func2.__code__.co_varnames
('x', 'y')

Hence the error you see: UnboundLocalError: local variable 'x' referenced before assignment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜