为什么它显示不同的输出?

nik*_*iko 1 python

x=4    
def func():           

       print("HELLO WORLD")          
       y=x+2    
       x=2    
       print (y)          
       print (x) # OUTPUT IS 6,2,2
       global x  # global declaration is done here
func()   
print (x) # outputs as 2 but why???? why not 4????
Run Code Online (Sandbox Code Playgroud)

为什么它将输出显示为6,2,2.实际上我在全局声明之前创建了print(x).但是我没有在全局声明之后更改x值,但是为什么它在func()之后将x值打印为2.是不是语句的顺序执行?或者它是否读取了函数中的整个代码,然后开始在线执行函数行?请清除以上程序.谢谢你提前

Ign*_*ams 9

global关键字向编译器指示该变量在整个函数中被视为全局变量.只要编译器注意到它,它在函数中出现的位置并不重要.