我在 python 中的 if-elif 语句中遇到问题

时间:2021-01-13 09:05:16

标签: 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")

这是我的输出: 该数字在索引 0 中

我想知道为什么不打印'2'的索引?它仅打印“1”的索引。

2 个答案:

答案 0 :(得分:2)

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,因此它不会转到 elif 语句。在上面的代码中,它将检查所有 if 语句以及第 1 个和第 3 个 if 语句是否被打印

答案 1 :(得分:0)

由于您将它们置于 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")
相关问题