Python:如何检查输入是否不等于二维数组中的任何项目?

Python : How to check if input is not equal to any item in a 2d array?

我试图检查输入的用户名是否等于列表中项目的第二个索引,我尝试使用 !=,但它仍然让相同的用户名被注册。代码有什么问题?

正在注册用户名:

user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]

name = input("Please enter your name : ")
while True:
     if name == '':
          name = input("Please enter your name : ")
     else:
          for user in user_list:
               if name != user[1]:
                    break # break out for loop
          else:
               print("This username has been registered")
               name = input("Please try another username : ") 
               continue # continue the while loop
          break # break out while loop
print("Username registered as",name)

已编辑:

!= 和 == 的结果似乎不同,== 有效。

登录用户名:

user_list = [['std1','Daniel'],['std2','Raymond'],['std3','Emanuel']]

name = input("Please enter your name : ")
while True:
     if name == '':
          name = input("Please enter your name : ")
     else:
          for user in user_list:
               if name == user[1]:
                    break # break out for loop
          else:
               print("Unregistered username")
               name = input("Please try another username : ") 
               continue # continue the while loop
          break # break out while loop
print("Logged in as",name)

下面这段代码可以解决很多问题。在您的代码中,即使我们用应该移入 for 循环的 else 修复了缩进错误,如果我们键入 Raymond,代码也不会工作。所以我提供了一个示例,它检查输入的 usr 是否在您的 user_list.

中的所有名称中
user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]

name = input("Please enter your name : ")
while True:
     if name == '':
          name = input("Please enter your name : ")
     else:
          for user in user_list:
               if name not in [lst[-1] for lst in user_list]:
                    break # break out for loop
          else:
               print("This username has been registered")
               name = input("Please try another username : ") 
               continue # continue the while loop
          break # break out while loop
print("Username registered as",name)

你非常接近!
你想做什么:如果 user_list 中有任何名称与新名称匹配,则跳出循环。
目前正在做什么:如果 user_list 中有任何名称与新名称不匹配,则跳出循环。
即,如果你输入 Daniel,因为 Daniel != Raymond,你会提前中断。

相反,如果新输入的名称不在名称列表中,您应该做的是中断:

user_list = [['usr1','Daniel'],['usr2','Raymond'],['usr3','Emanuel']]

name = input("Please enter your name : ")
while True:
    if name == '':
         name = input("Please enter your name : ")
    else:
        if name in [user[1] for user in user_list]:  # existing names list
            print("This username has been registered")
            name = input("Please try another username : ")
        else:
            break
print("Username registered as",name)