【Python基础】之全局变量(UnboundLocalError: local variable referenced before assignment)

来源:互联网 发布:网络在线麻将 编辑:程序博客网 时间:2024/05/01 12:41

count = 0def function():        count = count + 1    print(count)


Then we get: UnboundLocalError: local variable 'count' referenced before assignment

The reason this happens is because as soon as you write to a variable, that variable is automatically local to the function.

Here is the solution:

count = 0def function():    global count   #declare 'count' used in this function is the global one     count = count + 1    print(count)




原创粉丝点击