python - 在 Python 中赋值之前引用的局部变量

标签 python function variables scope

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

我不明白为什么。

最佳答案

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

使用 global 语句来处理:

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

来自 docs :

All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

关于python - 在 Python 中赋值之前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506947/

相关文章:

perl - 如何使用变量执行 Perl qx 函数

variables - 使用 Xpath for..in..return 时在 XSLT/XPath 中创建增量计数变量?

python - 如何根据权重对 networkx 中的边进行排序

python - 为什么我可以使用按位 AND 检查列表是否包含字典的键?

python - pytest fixture 中的 pytest-mock mock 者

c - 可以使传递的指针为空的函数

c - 请求不是结构或 union 的成员

函数内部的Python函数

python - flask 重定向多条路线

variables - 如何在标题中获取 cucumber 场景变量?