gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:43:04 24 4
gpt4 key购买 nike

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

注册用户名:

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)

最佳答案

你已经非常接近了!
您想要做什么:如果 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)

关于 python : How to check if input is not equal to any item in a 2d array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67814345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com