python 修改全局变量

函数内修改全局变量的两种不同情况

错误写法:

a = 0
def fun():
    a += 1
fun()
print(a)

报错:

UnboundLocalError: local variable 'a' referenced before assignment

正确写法:

a = 0
def fun():
    global a
    a += 1
fun()
print(a)

第二种情况: 嵌套

错误写法:

def fun():
    a = 0
    def fun1():
        a += 1
        
    fun1()
    print(a)

fun()

 报错:

UnboundLocalError: local variable 'a' referenced before assignment

正确写法:

def fun():
    a = 0
    def fun1():
        nonlocal a
        a += 1
        
    fun1()
    print(a)

fun()

注:在嵌套中若用glo

你可能感兴趣的:(python,python)