gpt4 book ai didi

python - 调用全局变量时无法解析的引用?

转载 作者:行者123 更新时间:2023-12-01 11:20:06 25 4
gpt4 key购买 nike

我打算在函数“In_queue”中调用两个全局变量(“head”和“tail”),结果成功调用了“head”,但未成功调用“tail”。错误是:

UnboundLocalError: local variable 'tail' referenced before assignment.

在另一个函数“Out_queue”中时,两个变量都成功调用。

编码:
tail = NODE(VALUE())
head = NODE(VALUE())
def In_queue():
try:
node = Create_node(*(Get_value()))
except:
print("OVERFLOW: No room availible!\n")
exit(0)
if not head.nextprt or not tail.nextprt:
tail.nextprt = head.nextprt = node
else:
tail.nextprt = node
tail = node
return None
def Out_queue():
if head.nextprt == tail.nextprt:
if not head.nextprt:
print("UNDERFLOW: the queue is empty!\n")
exit(0)
else:
node = head.nextprt
head.nextprt = tail.nextprt = None
return node.value
else:
node = head.nextprt
head.nextprt = node.nextprt
return node.value

最佳答案

好吧,那为什么头部能工作却尾部却没有呢?正如其他人在评论中提到的那样,将值分配给tail会导致将其视为局部变量。如果是head,您没有分配任何东西,那么解释器会在本地和全局范围内寻找它。为了确保tailhead都可以用作全局变量,您应该使用global tail, head。像这样:

def In_queue():
global tail, head
try:
node = Create_node(*(Get_value()))
except:
print("OVERFLOW: No room availible!\n")
exit(0)
if not head.nextprt or not tail.nextprt:
tail.nextprt = head.nextprt = node
else:
tail.nextprt = node
tail = node
return None

关于python - 调用全局变量时无法解析的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44879479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com