【问题标题】:Local variable referenced before assignment in Python在 Python 中赋值之前引用的局部变量
【发布时间】:2013-07-04 14:57:18
【问题描述】:
Truel=""
count = 0
finle_touch=False #true after it find the first 3 upperletter

# check if there is 1 lower letter after three upper letter
def one_lower(i):
    count=0
    if i == i.lower:
        finle_touch=True
        Truel=i

# check for 3 upper letter
def three_upper(s):
    for i in s:
        if count == 3:
            if finle_touch==True:
                break
            else:
                one_lower(i)
        elif i == i.upper:
            count +=1
            print(count) #for debug
        else:
            count ==0
            finle_touch=False

stuff="dsfsfFSfsssfSFSFFSsfssSSsSSSS......."
three_upper(stuff)
print(Truel)

所以我有很多关于“东西”的字符串,我喜欢找到被 3 个大写字母包围的 1 个小写字母。

但是当我运行这段代码时,我得到:

Traceback (most recent call last):
  File "C:\Python33\mypy\code.py", line 1294, in <module>
    three_upper(stuff)
  File "C:\Python33\mypy\code.py", line 1280, in three_upper
    if count == 3:
UnboundLocalError: local variable 'count' referenced before assignment

我不明白为什么。

【问题讨论】:

    标签: python function variables scope


    【解决方案1】:

    在这种情况下,使用 nonlocal 实际上会更好。尽可能少用全局。更多关于非本地的信息在这里docs.python.org/3/reference/simple_stmts.html#nonlocal

    【讨论】:

      【解决方案2】:

      由于count +=1这行python认为count是一个局部变量,当你使用if count == 3:时不会搜索全局范围。这就是你得到这个错误的原因。

      使用global 语句来处理:

      def three_upper(s): #check for 3 upper letter
          global count
          for i in s:
      

      来自docs:

      函数中的所有变量赋值都将值存储在本地 符号表;而变量引用首先在本地查找 符号表,然后在全局符号表中,然后在表中 的内置名称。因此,不能直接分配全局变量 函数中的值(除非在全局语句中命名), 尽管它们可能会被引用。

      【讨论】:

      • 谢谢,虽然我在函数外部定义 var 可以解决这个问题。所以每次我在函数中使用全局变量时,我都必须将它定义为全局变量?
      猜你喜欢
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多