user14965326
user14965326

Reputation:

I am having trouble in if-elif statements in python

Here's my code:

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

And here's my output: The number is in index 0

I want to know that why is it not printing the index of '2'? It is printing the index of '1' only.

Upvotes: 0

Views: 69

Answers (2)

Divyessh
Divyessh

Reputation: 2721

Since you have placed them in if-elif formation it will iterate through them one by one and if anyone of them is satisfying it wont print others. Since you have place

if lst.index('1') == 0 or lst.index('2') == 0:
    print("The number is in index 0")

in the beginning and it is True the code will end after printing the result. If you want all the correct results you should instead use this:

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

Upvotes: 0

SAI SANTOSH CHIRAG
SAI SANTOSH CHIRAG

Reputation: 2084

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

Since you are using elif once the if condition is true, it wont go to elif statements. In In above code it will check all the if statements and both the 1st and 3rd if statements are printed

Upvotes: 2

Related Questions