【问题标题】:Local variable referenced before assignment (but is it a bug?)赋值前引用的局部变量(但这是一个错误吗?)
【发布时间】:2022-01-07 09:53:32
【问题描述】:

我正在尝试编写一个适用于比特的加密函数,将它们相加得到一个新的比特组合,所以我有这个代码:

a=list("100010")
b=list("1100011")
n=[]
tmp=b[0]

for z in a:
    if int(z)==1:
        for y in b:
            if int(tmp)==1:
                tmp=0
            else:
                tmp=1
    else:
        for y in b:
            if int(y)==1:
                tmp=1
            else:
                tmp=0
    n.append(tmp)
    del tmp
print(n)

现在python返回:

Traceback (most recent call last):
  File "C:\Users\vitto\OneDrive\Desktop\python\test.py", line 24, in <module>
    main()
  File "C:\Users\vitto\OneDrive\Desktop\python\test.py", line 23, in main
    summing(temp)
  File "C:\Users\vitto\OneDrive\Desktop\python\test.py", line 8, in summing
    if int(tmp)==1:
UnboundLocalError: local variable 'tmp' referenced before assignment

我尝试使用全局变量作为另一个堆栈溢出页面的用户写道,我现在不应该使用全局变量来引用函数外部的变量,无论如何这个用户建议这样做:

a=list("100010")
b=list("1100011")
n=[]
tmp=b[0]
def test():
    global tmp
    for z in a:
        if int(z)==1:
            for y in b:
                if int(tmp)==1:
                    tmp=0
                else:
                    tmp=1
        else:
            for y in b:
                if int(y)==1:
                    tmp=1
                else:
                    tmp=0
        n.append(tmp)
        del tmp
test()

和以前一样的错误,所以我尝试了:

a=list("100010")
b=list("1100011")
n=[]
tmp=b[0]
def test(tmp):
    for z in a:
        if int(z)==1:
            for y in b:
                if int(tmp)==1:
                    tmp=0
                else:
                    tmp=1
        else:
            for y in b:
                if int(tmp)==1:
                    tmp=1
                else:
                    tmp=0
        n.append(tmp)
        del tmp
tmp=b[0]
test(tmp)

 

我可能在这里做错了,但我真的不知道是什么。我知道我已经插入了很多代码,但这是为了避免在网站上收到答案。

【问题讨论】:

    标签: python function variables debugging global


    【解决方案1】:

    您是在第一次迭代之后而不是循环之后删除tmp。如果你想在所有迭代结束后删除,这个工作:

    a=list("100010")
    b=list("1100011")
    n=[]
    tmp=b[0]
    
    for z in a:
        if int(z)==1:
            for y in b:
                if int(tmp)==1:
                    tmp=0
                else:
                    tmp=1
        else:
            for y in b:
                if int(y)==1:
                    tmp=1
                else:
                    tmp=0
        n.append(tmp)
    del tmp
    print(n)
    

    它给了[0, 1, 1, 1, 0, 1] 但是我不确定你需要删除,你可以让垃圾收集器完成它的工作而不删除变量。

    【讨论】:

    • 非常感谢您的快速回答,无论如何,tmp 不是垃圾收集器,它只能包含一个整数,应该是总和的第一个和第二个加数。跨度>
    • 我的意思是python垃圾收集器会自动删除tmp的数据,而不需要显式使用del
    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    相关资源
    最近更新 更多