[英]Break out of a python for loop using boolean flag, logic and indentation error
我有以下代码试图搜索用户名列表,并在第一次输出时简单地返回输出“在索引 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 语句(这就是我想要的)。
有人可以通过解释解决此问题的最有效方法来更正此代码。 这可能与布尔标志“找到”有关,我不明白为什么它没有爆发并进入 if 语句的底部。 提前致谢
您不需要那些布尔标志、基于范围的循环或额外的 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
你真的需要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")
while found==False:
使其循环直到found
变为True
。 因此,如果它没有找到您要查找的用户名,它会循环并再次询问您。
另外,如果您想查看列表中是否存在字符串,只需使用list.index()
方法:
username=input("Enter username:")
try:
i = usernames.index(username)
except ValueError:
print("Sorry,username not found")
else:
print("Username found in index:",i)
如果因为它被设计为只能达到第二你的代码根本不会达到第二个if
如果输入正确的用户名。
您必须决定要么继续询问用户名,直到输入正确的用户名(这就是您在while found == true
bit 中所做的)。
或者您只询问一次并查看是否找到,为此您需要删除while found == true
部分。
我明白你的意思可能是 DirtyBit 所做的: https ://stackoverflow.com/a/55183057
更好的版本是这个
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.