gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:56 25 4
gpt4 key购买 nike

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????

为什么它显示输出为 6,2,2。事实上,我在全局声明之前打印了 (x)。但是我在全局声明之后没有更改 x 值,但是为什么它在 func() 之后将 x 值打印为 2。这不是顺序执行语句吗?还是读取函数中的全部代码,然后开始在线执行函数行?请清除上述程序。提前致谢

最佳答案

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

关于python - 为什么它显示不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6646942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com