[英]Why is my for loop returning multiple outputs
为什么此代码返回多个输出代码
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”的字符串,它会返回字符串的 position 加上“错误”三遍,
如果我选择的字符串不满足条件,它会输出四次错误。
如果我不包括 else 部分,它只会输出字符串的 position 一次。
请问代码有什么问题,因为我需要包含其他部分
正如@Random Davis 在评论中提到的那样
a = [“w”,“u”,“i”,“r”]
count = 0 d = input("choose: ") for c in a: count += 1 if d == c: print(count) break else: print("wrong")
如果您要做的是在列表中查找元素的索引,请使用.index
方法:
a = ["w", "u", "i", "r"]
print(a.index("i")) -> 2
如果我选择一个满足这个条件“d==c”的字符串,它会返回该字符串的position加上“错误”三遍,
这是你想要做的吗?
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")
Output:
>>> choose: i
wrong
wrong
At index 2
wrong
你的逻辑很好,但我们需要在这里做一个小的修改,因为你知道当d==c的值时它会打印索引,如果我们需要停在那里,那么如果我们简单地增加计数,如果找到然后停止循环,请尝试:
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")
如果在列表 a 中找到 d,这将打印索引,否则它将打印“错误”
我认为您想要做的是在找到匹配项时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"
output 。
结果:
choose: i
3
choose: f
wrong
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.