【问题标题】:Why is my for loop returning multiple outputs为什么我的 for 循环返回多个输出
【发布时间】:2022-01-04 17:04:06
【问题描述】:

为什么这段代码会返回多个输出 代码

a = ["w", "u", "i", "r"]


count = 0
d = input("choose: ")
for c in a:
    count += 1
    if d == c:
        print(count)
    else:
        print("wrong")      

如果我选择一个满足这个条件“d==c”的字符串,它会返回该字符串的位置加上“错误”三遍,

如果我选择一个不满足条件的字符串,它会输出四次错误。

如果我不包含 else 部分,它只会输出字符串的位置一次。

请问代码有什么问题,因为我需要包含 else 部分

【问题讨论】:

  • 您需要将break 语句放在prints 之后,这样循环才会停止。
  • 想要代码做什么?你想让它查看整个字符串,然后打印完整的计数器或“错误”吗?
  • 你不return 任何东西(你不能,因为你不在函数内部),你只是print 它。
  • @samwise 是的,我想要那个,只需打印索引或错误而不是伴随的“错误”。而且我不想用索引函数,想自己写索引函数
  • 然后看我的回答——关键是你不希望“错误”的情况在循环的 end 之前发生,因为不可能在您查看所有个字母之前知道输入是否错误。

标签: python python-3.x loops for-loop


【解决方案1】:

如果我选择一个满足这个条件“d==c”的字符串,它会返回该字符串的位置加上“错误”三倍,

这是你想要做的吗?

a = ["w", "u", "i", "r"]

d = input("choose: ")

for index, c in enumerate(a):
    if d == c:
        print(f"At index {index}")
    else:
        print("wrong") 

输出:

>>> choose: i
wrong
wrong
At index 2
wrong

【讨论】:

    【解决方案2】:

    如果您要在列表中查找元素的索引,请使用.index 方法:

    a = ["w", "u", "i", "r"]
    print(a.index("u"))  -> 1
    

    如果元素不在列表中,它会返回错误,您可以通过使用try-except 或检查元素是否在列表中来克服它:

    i = input("choose: ")
    if i in a:
        print(a.index(i))
    else:
        print("wrong")
    

    try:
        print(a.index(i))
    except ValueError:
        print("wrong")
    

    【讨论】:

      【解决方案3】:

      你的逻辑很好,但是我们需要在这里做一个小修改,因为你知道当 d==c 的值时它会打印索引,如果我们需要 stop 就在那里,如果我们简单地增加 count 并且如果找到然后 停止循环, 请尝试:

      a = ["w", "u", "i", "r"]
      count = 0
      d = input("choose: ")
      for c in a:
          if d == c:
              print(count)
              break
          count += 1
      else:
         print("wrong") 
      

      如果 d 在列表 a 中找到,这将打印索引,否则它将打印“错误”

      【讨论】:

        【解决方案4】:

        我认为你想要做的是找到匹配项时break,并取消缩进else

        a = "wuir"
        count = 0
        for c in a:
            count += 1
            if d == c:
                print(count)
                break
        else:
            print("wrong")
        

        取消缩进else 使其成为for 语句的一部分,而不是if。这意味着只有当整个 for 循环在没有 break 的情况下完成时才会执行它——这意味着如果 d == c 条件从未出现过,您只会在循环的最后得到 "wrong" 输出见了。

        结果:

        choose: i
        3
        
        choose: f
        wrong
        

        【讨论】:

          猜你喜欢
          • 2018-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-12
          • 2022-01-23
          相关资源
          最近更新 更多