我有以下代码,试图搜索用户名列表,并在第一次输出时返回输出“在索引i中找到”或“找不到用户名”。
usernames=["u1","u2","u3"]
found=False
while found==False:
username=input("Enter username:")
for i in range(len(usernames)):
if username==usernames[i]:
found=True
break
if found==True:
print("Username found in index:",i)
else:
print("Sorry,username not found")
如果用户名是正确的,当前的代码似乎有效,但是如果使用了错误的数据,例如23234,那么它会重复问题并且不会跳转到代码底部的if语句(这就是我想要的)。
有人可以更正此代码,并解释最有效的方法来解决这个问题。它可能与布尔标志'found'有关,我不明白为什么它不会突破并转到底部if语句。提前致谢
你真的需要while
块吗?
usernames=["u1","u2","u3"]
index = 0
found = False
username = input("Enter username:")
for i in range(len(usernames)):
if username == usernames[i]:
found = True
index = i
break
if found:
print("Username found in index:",index)
else:
print("Sorry,username not found")
您不需要那些布尔标志,基于范围的循环或额外的if条件:
usernames=["u1","u2","u3"]
while True:
user = input("Enter username: ")
if user in usernames:
print("Username found at Index: {}".format(usernames.index(user)))
break
else:
print("Sorry, username not found. Try again")
编辑:
但是如果你必须继续使用当前使用for循环的方法,那么在外部for循环中放置一个else块并在找到时中断:
usernames = ["u1","u2","u3"]
found = False
while found == False:
username = input("Enter username: ")
for i in range(len(usernames)):
if username == usernames[i]:
print("Username found at Index: {}".format(i))
break
else: # not and indentation error
print("Sorry, username not found. Try again")
编辑2 :(没有布尔标志)
usernames = ["u1","u2","u3"]
while True:
username = input("Enter username: ")
for i in range(len(usernames)):
if username == usernames[i]:
print("Username found at Index: {}".format(i))
break
else: # not and indentation error
print("Sorry, username not found. Try again")
输出(在所有情况下):
Enter username: 2334
Sorry, username not found. Try again
Enter username: u2
Username found at Index: 1
您的代码将永远不会达到第二个,因为它只是为了输入正确的用户名而只能到达第二个if
。
您必须决定继续询问用户名,直到输入正确的用户名(这就是您在while found == true
位中执行的操作)。
或者你只问一次,看看是否找到了,因为你需要删除while found == true
部分。
我看到你的意思可能就是DirtyBit所做的:https://stackoverflow.com/a/55183057
while found==False:
让它循环直到found
成为True
。因此,如果它找不到您要查找的用户名,它会循环并再次询问您。
此外,如果您想查看列表中是否存在字符串,只需使用list.index()
method:
username=input("Enter username:")
try:
i = usernames.index(username)
except ValueError:
print("Sorry,username not found")
else:
print("Username found in index:",i)
这是一个更好的版本
usernames = ["u1", "u2", "u3"]
while True:
username = input("Enter username:")
if username in usernames:
print("Username found in index:", usernames.index(username))
break
else:
print("Sorry,username not found")
根据要求编辑:
usernames = ["u1", "u2", "u3"]
found = False
while found is False:
found = False
username = input("Enter username:")
for i in range(len(usernames)):
if usernames[i] == username:
print("Username found in index:", i)
found = True
break
if found is False:
print("Sorry,username not found")