【问题标题】:Python NameError issuePython NameError 问题
【发布时间】:2017-12-10 17:54:52
【问题描述】:

我的代码有问题,说我有一个 NameError 并且我的名字没有定义。虽然据我所知,我的名字已经被定义了。

# Create UAS database list that was displayed in the file
uas_Stock = [["CS116",1],["CS117",1],["CS118",1],["CS119",1],["CS120",1]]

# Ask user to select which UAV they want to check out.
uas_out = str(input("Which UAV would you like to checkout? "))

# Append stock list to show UAS is checked out
if uas_out == CS116:
    list.insert(0,1, "0")
elif uas_out == CS117:
    list.insert(1,1, "0")
elif uas_out == CS118:
    list.insert(2,1, "0")
elif uas_out == CS119:
    list.insert(3,1, "0")
else:
    list.insert(4,1, "0")

我希望结果采用 uas_out 值并运行 if/else 语句并执行它所说的任何一个。然后将附加列表以给出某个列表的值 0 而不是 1。

我在输入 uas_out 的值时遇到的错误是:

NameError: name '(whatever uas_out is/CS116/117/118/119/120)' is not defined.

【问题讨论】:

    标签: python-3.x list insert nameerror


    【解决方案1】:

    CS116 等是字符串,不是变量,需要用引号括起来:

    if uas_out == 'CS116':
        list.insert(0,1, "0")
    elif uas_out == 'CS117':
        list.insert(1,1, "0")
    elif uas_out == 'CS118':
        list.insert(2,1, "0")
    elif uas_out == 'CS119':
        list.insert(3,1, "0")
    else:
        list.insert(4,1, "0")
    

    【讨论】:

    • 非常感谢。我已经看这个太久了。我想这就是为什么我没有看到它有多简单。
    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2021-10-10
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多