python局部变量定义后(内有global),无法打印

cnt = 1
def func(x):
global cnt
tmp = cnt
cnt = x
x = tmp
func(2)
print (cnt)

#以上输出为2
将第一句cnt = 1 剪掉后,只用局部变量
def func(x):
global cnt
tmp = cnt
cnt = x
x = tmp
func(2)
print (cnt)
而因为变量里面加了global,而且也调用了func(2),为什么最下面print(cnt)后输出为出错?
而将内部变量变一下
def func(x):
global cnt
cnt = x
func(2)
print(cnt)
这样输出值又变回2了,谁能讲讲原理吗?

附言 1  ·  2个月前

本人己想通,既然要删除全局变量cnt = 1,那么局部变量CNT=多少就都没有意义了,也不用global强制变全局了。

Jason990420
最佳答案
def func(x):

    global cnt

    tmp = cnt
    cnt = x
    x = tmp

func(2)
print (cnt)
Traceback (most recent call last):
  File "<module2>", line 9, in <module>
  File "<module2>", line 5, in func
NameError: name 'cnt' is not defined. Did you mean: 'int'?

虽然宣告了 cnt 为 global, 但在语句 tmp = cnt中要引用cnt的值, 这个时候, cnt并未定义, 如何能引用其值 ?! 所以就会出错了 !

2个月前 评论
讨论数量: 1
Jason990420
def func(x):

    global cnt

    tmp = cnt
    cnt = x
    x = tmp

func(2)
print (cnt)
Traceback (most recent call last):
  File "<module2>", line 9, in <module>
  File "<module2>", line 5, in func
NameError: name 'cnt' is not defined. Did you mean: 'int'?

虽然宣告了 cnt 为 global, 但在语句 tmp = cnt中要引用cnt的值, 这个时候, cnt并未定义, 如何能引用其值 ?! 所以就会出错了 !

2个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!