Home > other >  Python skipping if statement even though its True
Python skipping if statement even though its True

Time:03-03

I am trying to create a loop that checks the contents of a list of lists for a name and returns the index of the name if true. When I write the code without the else statement it works but when I add the else statement it skips the if condition and just applies the else condition. Can anyone tell me where I am going wrong?

outer_list = [['Mother', 'Sharon', 'f', 35, '170cm'], ['Father', 'Bruce', 'm', 37, '189cm'], ['Daughter', 'Amelia', 'f', 10, '137cm']]

name = 'Sharon'
index = -1
index_pos = 0

for inner_list in outer_list:
    if name in inner_list:
        index  = 1
        index_pos = index
    else:
        index_pos = -1

print(index_pos)

CodePudding user response:

In my opinion, you should

  1. put index = 1 before the if statement
  2. initilize index_pos as -1, and drop else statement

Then it should be correct to print or return index_pos

CodePudding user response:

When you wrote your code without else, like this

for inner_list in outer_list:
    if name in inner_list:
        index  = 1
        index_pos = index

The variable index_pos is assigned only if it finds a match in any of the sublists. And then on its not modified.

But when you add an else case like

else:
    index_pos = -1

You are resetting your position. Simply think, you found a sublist with a name in it, so you assigned the position and went to next sublist, there you did not find the name, and now the else works - resetting the already found position. This is where it goes wrong.

You can use a break statement, if you think you need only the position of the name , that occurs first. Then it will not check further in other sublists for eg.

for inner_list in outer_list:
    if name in inner_list:
        index  = 1
        index_pos = index
        break; #This ends the search!

You don't need the else statement, unless you want to force the check, the name should exist in all lists.

CodePudding user response:

Just add a break in your if block

CodePudding user response:

Your question not quite clear, but I am guessing you want the index = 1 to run, for both cases right? If so, then:

for inner_list in outer_list:
    index  = 1
    if name in inner_list:
        index_pos = index
    else:
        index_pos = -1
  • Related