【问题标题】:Break out of a python for loop using boolean flag, logic and indentation error使用布尔标志、逻辑和缩进错误打破 python for 循环
【发布时间】:2019-08-06 13:20:31
【问题描述】:

我有以下代码试图搜索用户名列表,并在第一个输出时简单地返回输出“在索引 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 语句。提前致谢

【问题讨论】:

  • 放置一个else块来处理错误数据
  • “缩进错误”?
  • 这并不能回答您关于打破嵌套循环的问题,但考虑一种更简单的方法来确定字符串是否在列表中:if username in usernames:
  • 去掉外部的while循环...?
  • 你根本不需要 while 循环,只要找到匹配项就设置为 true 就可以了。

标签: python list loops boolean break


【解决方案1】:

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)

【讨论】:

  • 是的,它变成了“真”——在上面的代码中,当找到用户名时。 (那一点有效)。什么不起作用,在另一种情况下(找不到时),我希望它跳转到下面的代码(if 语句)并说“对不起,在列表中找不到用户名”
  • 就像我说的,while found==False: 语句使它像这样循环。如果您不希望它循环,只需摆脱这个 while 循环!
【解决方案2】:

您不需要那些布尔标志、基于范围的循环或额外的 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")

EDIT 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

【讨论】:

  • 我被难住了! - 谢谢 - 这行得通,但我不明白这一切。为什么'else'在'for'的缩进级别而不是原始的'if'。我显然不明白 python 缩进。我尝试过完全相同的事情,所以在逻辑上是正确的,但我的 else 在同一行是'if'并且它重复了块
  • @MilesDavis 不,这不是错误。 Python 有 for/else 结构。阅读这里book.pythontips.com/en/latest/for_-_else.html
  • @MissComputing 可以这样想,如果else 块在if 级别,如果用户名没有放在第一个索引上,那就是真的。 for 循环也有一个 else 子句!
  • 我的错,从未使用过 for/else 语句。
  • 优秀 - 不知道!我认为是 python 独有的......!
【解决方案3】:

如果输入正确的用户名,您的代码将永远不会到达第二个 if,因为它被设计为仅到达第二个 if

您必须决定是否继续询问用户名,直到输入正确的用户名(这就是您在 while found == true 位中所做的事情)。

或者您只询问一次,看看是否找到,因为您需要删除 while found == true 部分。

我明白你的意思可能是 DirtyBit 所做的:https://stackoverflow.com/a/55183057

【讨论】:

  • 谢谢您-虽然不确定它是否回答了这个问题。您能否更正代码并发布一个解决方案,使其符合问题的要求,即“如果用户名存在,它会打印“存在于索引中..”,如果不是“对不起,没有用户名”。我不想使用“ if username in usernames" 因为我们需要使用for循环来演示
【解决方案4】:

一个更好的版本是这个

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")

【讨论】:

  • 是的,这很好——但如前所述,我想使用 for 循环。我想使用 for 循环解决问题。 (这是为了教授算法的目的)
  • 它不起作用 - 它不必要地重复“找到用户名或对不起用户名”
  • @MissComputing 抱歉,复制错误 - 粘贴。立即尝试
【解决方案5】:

你真的需要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")

【讨论】:

  • 那行不通。 NameError:未定义名称“找到”
  • for index, candidate in enumerate(usernames): if username == candidate:... 会比遍历范围更惯用。
  • if found:,而不是if found == True:
  • 是的,有效!但这让我想知道最有效的方法是否完全没有标志。如果没有 found=false 和 for 循环中的 if 语句,是否可以做到这一点!?
  • @MissComputing 是的,它可以。但效率几乎相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多