NameError: name "user_choice1" is not defined

NameError: name "user_choice1" is not defined

我正在尝试一个简单的程序并不断收到此特定错误:

line 34, in <module>
user_choice1 == input("Do you want to exit or continue searching?")
NameError: name 'user_choice1' is not defined

这是导致错误的代码片段:

while True:
choice = input("Do you want to add items?")
if choice == "y":
    add_items()
    more = input("Do you want to add more items?")
    if more == "y":
        add_items()
    else:
        while True:
            user_choice = input("Adding items finished. Do you want to search items or exit?")
            if user_choice == "search":
                search_item()
                while True:
                    user_choice1 == input("Do you want to exit or continue searching?")
                    if user_choice1 == "continue":
                        search_item()
                        continue 
                    elif user_choice1 == "exit":
                        sys.exit()
                    else:
                        break                
            elif user_choice == "exit":
                sys.exit
            else:
                continue


elif choice == "n":
    search_item()
    while True:
        user_choice2 = input("Searching finished. Do you want to continue or exit?")
        if user_choice2 == "continue":
            break
            continue
        elif user_choice2 == "exit":
            sys.exit()
        else:
            continue

elif choice == "exit":
    sys.exit()

else:
    print("Invalid Choice")

导致此错误的原因是什么?我正在使用 Python 3.5.2。 另外,有没有更好的方法来编写这段代码,有没有办法优化这段代码?

在 Python 中,使用双等号 == 是对等式的逻辑测试。使用单等号,= 是一个赋值。

所以你所做的是告诉 Python 检查 user_choice1 是否等于 input 语句。它正确地告诉你你还没有定义那个变量。

x = 4 #assigns the value 4 to x
y = 4 #assigns the value 4 to y
x == y #returns True
x == 7 #returns False

您似乎在多个地方重复了此错误,因此请返回并为所有这些地方切换到一个相同的位置。