python - 我怎样才能避免这个 "variable referenced before assignment"?

标签 python python-2.7

<分区>

遇到以下问题。这可能是一个简单的解决方案,之前可能曾在这里询问过,但我找不到。

def a():
    liA = []
    def b():
        for i in liA:
            i += 1
        liB = generateList()
        for i in liB:
            i -= 1
        liA = liB

    def generateList():
        return [1,2,3,4]

    b()

a()

UnboundLocalError:赋值前引用了局部变量'liA'

最佳答案

b() 函数中的

liA 变量从未初始化。

因此,您应该按照以下方式编辑代码:

def a():
    liA = []
    def b(liA):
        for i in liA:
            i += 1
        liB = generateList()
        for i in liB:
            i -= 1
        liA = liB

    def generateList():
        return [1,2,3,4]

    b(liA)

a()

希望我对你有帮助!

关于python - 我怎样才能避免这个 "variable referenced before assignment"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32305262/

相关文章:

python - 导入错误: cannot import name 'FileStorage' from 'werkzeug'

python-2.7 - 使用 Python 进行计算逻辑回归,不同的样本大小

Python Pandas read_sql_query “' NoneType' object is not iterable”错误

mysql - 使用注释 django

python - 如何在 Bluemix 上的 Spark 即服务中从 Python 笔记本读取存储在对象存储中的 SQLite 文件?

python - 让 pubsubhubbub 集线器工作

python - 使用 Python 3 的 FTP 文本文件为空

python - 如何在路由函数中启用仅限开发的行为

python - 无法在 Windows 7 上导入 ctypes

Python - 简单的 for 循环未按预期工作(使用请求模块)