python报错问题:UnboundLocalError: local variable ‘num‘ referenced before assignment

阅读 61

2022-02-01

num=0

def outside():
    print(num)


outside()

上面代码,直接使用全局,调用函数,打印结果为0
当在函数里对num进行加1操作,没有加全局,报错:UnboundLocalError: local variable ‘num’ referenced before assignment,代码如下

num=0

def outside():
    num+=1
    print(num)
outside()

函数里对全局num进行运算,存储位置改变,函数引用全局进行运算,不改变全局的,需要使用global,代码如下

num=0

def outside():
    global num
    num+=1
    print(num)
outside()

打印结果为1

精彩评论(0)

0 0 举报