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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With