2016-08-13 91 views
-4

我想了一个简单的程序,并不断收到此特定错误:NameError:名字“user_choice1”没有定义

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。 此外,有没有更好的方式来编写代码,有没有一种方法来优化此代码?

回答

1

在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 

它看起来像你在几个地方重复这个错误,所以回去,并切换到一个平等的所有人。

+0

我不知道我错过了这个。我觉得很愚蠢。感谢兄弟的帮助。我想我需要一些睡眠:) –

+1

我知道你的意思,但它更准确地说,你告诉Python来检查'user_choice1'是否等于'input'函数返回的值。顺便说一句,我们通常不会为编写错误的问题编写完整的答案,因为它们不太可能帮助未来的读者带来类似的问题:他们不太可能通过谷歌搜索找到这个问题。 –

相关问题