Local variable referenced before Python
我有以下代码:
1 2 3 4 5 6 7 8 9 | def popLast(aLinkedList): ptr = aLinkedList while ptr != None: if ptr['next']['next'] == None and ptr['next'] != None: del_node = ptr['data'] ptr['next'] = ptr['next']['next'] ptr = ptr['next'] return (del_node,ptr) |
当我放
1 2 3 4 5 | myLinkedList = createList(['a', 'b', 0, [1, 2]]) for i in range(getLength(myLinkedList)): (a, myLinkedList) = popLast(myLinkedList) print(a, end =", new list:") printList(myLinkedList) |
它一直在给我
UnboundLocalError: local variable 'del_node' referenced before assignment
当我只使用
如果传入空列表,则不会初始化del_节点。这就是导致错误的原因。要更改此设置,请先将del_节点初始化为无:
1 2 3 4 5 | def popLast(aLinkedList): ptr = aLinkedList del_node = None while ptr is not None: ... |