Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check the whole loop before going to the else statement

How do I run through the whole loop and then after go to else statement, if the if condition is false?

The output is:

No

No

Yes

But I only want it to jump to the else statement if all of the values does not equal!

test_1 = (255, 200, 100)
test_2 = (200, 200, 100)
test_3 = (500, 50, 200)

dict = {"test_1":test_1,
        "test_2":test_2,
        "test_3":test_3}


for item in dict:
   if dict[item] == (500, 50, 200):
        print('Yes')
   else:
        print('No')

So basicly the output should say, because one of the values was true.

Yes

like image 886
Frederik Avatar asked Dec 15 '22 17:12

Frederik


2 Answers

You need to run the loop until you find a matche. You can use any function for this purpose, like this

if any(dict_object[key] == (500, 50, 200) for key in dict_object):
    print('Yes')
else:
    print('No')

We pass a generator expression to any function. The generator expression takes each and every item from the dict and checks if it is equal to (500, 50, 200). The moment it finds a match, the any will return True immediately and the rest of the iterations will not even take place. If none of the items match (500, 50, 200), any will return False and the No will be printed.


Edit: After a lengthy discussion with the OP in the chat, he actually wanted to know the item which matches as well. So, the better solution would be to go with for..else like in the other answer by NPE, like this

for key in dict_object:
   if key.startswith('test_') and dict_object[key] == (500, 50, 200):
        # Make use of `dict_object[key]` and `key` here
        break
else:
    print('No matches')
like image 145
thefourtheye Avatar answered May 13 '23 16:05

thefourtheye


But I only want it to jump to the else statement if all of the values does not equal!

Python's for-else construct can be used to do exactly that:

for item in dict:
   if dict[item] == (500, 50, 200):
        print('Yes')
        break
else:
    print('No')

For further discussion, see Why does python use 'else' after for and while loops?

However, in this particular instance I would not use an explicit loop at all:

print ("Yes" if (500, 50, 200) in dict.values() else "No")
like image 34
NPE Avatar answered May 13 '23 17:05

NPE