[英]Why am I getting “UnboundLocalError” in this code?
I am getting UnboundLocalError: local variable 'prev' referenced before assignment on the given code below我收到 UnboundLocalError: local variable 'prev' 在对下面给定代码赋值之前引用
class Node:
def __init__(self,value,next=None):
self.value=value
self.next=next
class MyList:
def __init__(self,a):
self.head=None
tail=None
for i in a:
n=Node(i,None)
if self.head is None:
self.head=n
tail=n
else:
tail.next=n
tail=n
def showList(self):
n=self.head
if n==None:
print("Empty list")
while n!=None:
print(n.value)
n=n.next
def isEmpty(self):
n=self.head
if n is None:
print("True")
else:
print("False")
def clear(self):
while(self.head!=None):
temp=self.head
self.head=self.head.next
temp=None
def insert(self, newElement):
node = self.head
while node:
if node.value == newElement:
print("Value already exists")
return False
prev = node
node = node.next
if prev:
prev.next = Node(newElement)
else:
self.head = Node(newElement)
return True
list1 = [1, 2, 3, 4, 5]
linklist = MyList(list1)
linklist.showList()
linklist.isEmpty()
linklist.clear()
linklist.showList()
linklist.insert(6)
linklist.showList()
If I remove the clear(self) function the code is working perfectly but when it is not removed an error is showing in the insert(self,newElement) function.如果我删除 clear(self) 函数,则代码运行良好,但是当它没有删除时,insert(self,newElement) 函数中会显示错误。 It is showing它正在显示
Traceback (most recent call last):
File "c:\Users\acer\Desktop\Untitled-1.py", line 65, in <module>
linklist.insert(6)
File "c:\Users\acer\Desktop\Untitled-1.py", line 51, in insert
if prev:
UnboundLocalError: local variable 'prev' referenced before assignment
PS C:\Users\acer>
In your insert
method, you need to initialize prev
to None
before entering the loop.在您的insert
方法中,您需要在进入循环之前将prev
初始化为None
。 Otherwise, if the loop exits before the first iteration (ie, if self.head
is None
), then prev
will be undefined, which is what Python is telling you.否则,如果循环在第一次迭代之前退出(即,如果self.head
是None
),那么prev
将是未定义的,这就是 Python 告诉你的。 Just add the initialization like so:只需像这样添加初始化:
def insert(self, newElement):]
prev = None
node = self.head
while node:
...
In your insert()
method if you do not enter the while
loop then the prev
variable will not be initialised.在您的insert()
方法中,如果您不进入while
循环,则不会初始化prev
变量。
What you need to do is initialise it to something at the start of your insert()
method or ensure that you are always entering the while
loop.您需要做的是在insert()
方法开始时insert()
其初始化为某些内容,或者确保您始终进入while
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.