NameError: name 'last' is not defined (though it's actually defined)

NameError: name 'last' is not defined (though it's actually defined)

我在 python 上收到这个奇怪的错误:我定义了一个名称(在本例中,last),但它说尚未定义.

代码:

name = input("Insert name here: \n")
list = list(name)
last = list[len(list)-1]    ### here is when it's defined

print("--\n")

while not len(list) == 1:

    if last == " ":    ### here is when it's first required
        del(last)

    print(("".join(list)))
    del(last)

print(("".join(list)))

错误响应:

Traceback (most recent call last):
  File "C:/Users/ocari/OneDrive/Documents/Python things/Decompor.py", line 9, in <module>
    if last == " ":
NameError: name 'last' is not defined

我该如何解决?

(顺便说一句,如果我在需要的每一行中将名称 'last' 交换为所需的定义(当前为 'list[len(list)-1]'),那么代码就可以工作。这证明了问题不是它的定义,而是另一种问题)

当您的列表超过 1 项时
您的 'last' 将被删除超过 1 次(因为它在循环中)
如果你想删除列表中的最后一项
你可以使用 pop
试一试

name = input("Insert name here: \n")
list = list(name)
last = list[len(list)-1]    ### here is when it's defined

print("--\n")

while not len(list) == 1:
    if list[-1] == ' ' :
      list.pop()
    if len(list) == 1 :
        break
    list.pop()
    print(("".join(list)))

一旦你del last,它就不再定义了。您在循环中的两个点执行此操作。然后在下一次循环中,你再次尝试 del last。由于不再定义,这是一个错误。