python全局变量的修改

举个例子。外部函数定义了count变量,而后在内部函数中去使用并修改它。
可以看到,我们可以打印它,但是不能修改它。
在这里插入图片描述在这里插入图片描述

原因

python 不可变变量(比如str, int, double,tuple这些),如果在外部函数申明,那么内部只能使用不能修改,如果想要修改只能在外部申明的时候加上global关键字, 在使用的时候也要先说明一下:

while True:
    try:
        n = input()
        global count
        count =1
        def inner():
        #说明使用的count变量为全局的不是局部的
            global  count
            print(count)
            count += 1
            print(count)
        inner()
    except:
        break

而python中的可变变量(比如list,dict)外部申明后内部函数可以进行修改。

猜你喜欢

转载自blog.csdn.net/dpengwang/article/details/92951242