0

If condition with and operator in loop

Is below code not supposed to work. I wanted to print both the words using if condition from the list. Works fine with or operator. words = ["hello", "world", "spam", "eggs"] for word in words: if word == 'hello' and word == 'eggs': print(word + "!") break

22nd May 2021, 10:45 AM
Prabuddh Bhatia
Prabuddh Bhatia - avatar
6 Answers
+ 5
Your if-condition implies that 'word' is equal to "hello" AND 'word' is equal to "eggs". Any string can't be equal to "hello" and "eggs" at the same time. So the condition is never true and the code inside the if-block is never executed.
22nd May 2021, 10:55 AM
XXX
XXX - avatar
+ 5
word == 'hello' and word == 'eggs' is impossible. x% 2== 1 and x > 4 is possible. What exactly do you want your code to do?
22nd May 2021, 11:11 AM
David Ashton
David Ashton - avatar
+ 4
Is your expected output hello! eggs! ? If so, you have to use 'or'. 'and' doesn't make sense.
22nd May 2021, 11:15 AM
David Ashton
David Ashton - avatar
+ 3
Ok. Thanks a lot guys 🙂
22nd May 2021, 11:17 AM
Prabuddh Bhatia
Prabuddh Bhatia - avatar
+ 1
But in below example by Sololearn there are 2 values that can be taken by x (5 and 7) and only 1 is printed because of break statement. Also, what to do if I want to print any 2 specific words out of these 4 in the list in my above example. list = [2, 3, 4, 5, 6, 7] for x in list: if ( x% 2== 1 and x > 4): print (x) break
22nd May 2021, 11:03 AM
Prabuddh Bhatia
Prabuddh Bhatia - avatar
+ 1
Ok. Just wanted to check if words I specified were in the list and print them.
22nd May 2021, 11:14 AM
Prabuddh Bhatia
Prabuddh Bhatia - avatar