Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference when calling a global variable?

I intended to call two global variables ('head' and 'tail') in the function 'In_queue', and turned out to call 'head' successfully but 'tail' not. The error is:

UnboundLocalError: local variable 'tail' referenced before assignment.

While in another function 'Out_queue', the two variables both called successfully.

The code:

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
like image 385
Xu Chengzhe Avatar asked Jul 03 '17 06:07

Xu Chengzhe


1 Answers

Ok, so why did head work but tail didn't? As others have mentioned in comments, assigning value to tail caused it to be treated like local variable. In case of head, you didn't assign anything to it, so the interpreter looked for it in local and global scope. To make sure both tail and head works as globals you should use global tail, head. Like this:

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
like image 115
Maciek Avatar answered Nov 15 '22 14:11

Maciek