首页 > 解决方案 > Python UnboundLocalError,是什么原因造成的?

问题描述

在python中我写道:

registered_to = 0

def execute_data():
    registered_to += response.text.count("<div class=\"info-msg\">")

但我得到:

registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment

标签: pythonpython-3.x

解决方案


这是你想要的吗?

registered_to = 0

def execute_data():
    global registered_to
    registered_to += response.text.count("<div class=\"info-msg\">")

每当您希望从非全局范围(如函数)修改/创建全局变量时,都必须使用global关键字。如果您只是使用非全局范围内的全局变量而不修改它,则无需使用关键字。

例子

  1. 在非全局范围内使用全局变量但不修改它
wish = "Hello "

def fun():
    print(wish)

fun()
  1. 在非全局范围内使用全局变量并对其进行修改
wish = "Hello "

def fun():
    word += "World"
    print(wish)

fun()

推荐阅读