Python checks the entire loop before moving on to the else statement

How can I execute the whole loop and then go to the statement elseif the condition ifis wrong?

Conclusion:

No

No

Yes

But I just want it to jump to the else statement if all values ​​are 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 the main conclusion I must say, because one of the meanings was true.

Yes

+4
source share
3 answers

You need to start the cycle until you find the match. You can use anyfor this purpose, for example

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

any. dict , (500, 50, 200). , , any True , . (500, 50, 200), any False No.


: OP , . , for..else, NPE,

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')
+7

, else, !

Python for - else :

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

. python "else" while while?

:

print ("Yes" if (500, 50, 200) in dict.values() else "No")
+4

Perhaps use a statement in:

item_appears_in_dict = item in dict.values()
print "Yes" if item_appears_in_dict else "No"
+1
source

Source: https://habr.com/ru/post/1570758/


All Articles