[英]I am having trouble in if-elif statements in python
这是我的代码:
import random
lst = ['1', '2', '3', '4']
if lst.index('1') == 0 or lst.index('2') == 0:
print("The number is in index 0")
elif lst.index('1') == 1 or lst.index('2') == 1:
print("The number is in index 1")
elif lst.index('1') == 2 or lst.index('2') == 2:
print("The number is in index 2")
elif lst.index('1') == 3 or lst.index('2') == 3:
print("The number is in index 3")
这是我的 output:号码在索引 0 中
我想知道为什么不打印“2”的索引? 它仅打印索引“1”。
import random
lst = ['1', '2', '3', '4']
if lst.index('1') == 0 or lst.index('2') == 0:
print("The number is in index 0")
if lst.index('1') == 1 or lst.index('2') == 1:
print("The number is in index 1")
if lst.index('1') == 2 or lst.index('2') == 2:
print("The number is in index 2")
if lst.index('1') == 3 or lst.index('2') == 3:
print("The number is in index 3")
由于您在 if 条件为真后使用 elif,因此它不会 go 到 elif 语句。 在上面的代码中,它将检查所有 if 语句以及打印的第一个和第三个 if 语句
由于您已将它们放置在 if-elif 格式中,它将一个接一个地遍历它们,如果其中任何一个令人满意,它就不会打印其他的。 既然你有位置
if lst.index('1') == 0 or lst.index('2') == 0:
print("The number is in index 0")
在开始时它是 True 代码将在打印结果后结束。 如果你想要所有正确的结果,你应该使用这个:
if lst.index('1') == 0 or lst.index('2') == 0:
print("The number is in index 0")
if lst.index('1') == 1 or lst.index('2') == 1:
print("The number is in index 1")
if lst.index('1') == 2 or lst.index('2') == 2:
print("The number is in index 2")
if lst.index('1') == 3 or lst.index('2') == 3:
print("The number is in index 3")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.