【发布时间】: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