2017-07-03 30 views
1

我打算在函数'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 
+1

您分配给tail,使其成为本地:'tail = node'。 UnboundLocalError有大量问题,我建议进行一些更多的研究。 – jonrsharpe

+0

如果您分配给一个变量,它变成本地。如果你想分配给全局尾部变量,你需要在函数内部放置'global tail'。 – pschill

回答

1

好了,为什么头的工作,但尾巴没有?正如其他人在评论中提到的那样,将值分配给tail会导致它被视为局部变量。如果是头,你没有分配任何东西,所以解释者在本地和全球范围内寻找它。为确保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