How to use 'if statement' with 'or' operator in python

Question:

I have list that contains some value now i want to check it for empty string and Null values. So i am using below code for same but output is not coming correct.
On checking for ” empty string it is giving output ‘not nice’
Its working fine for ‘Null’ value but not considering it for ” empty values.
Any help would be appreciated.

y=['','']
if ('Null' or '') in y:
    print ('nice')
else:
    print('not nice')
Asked By: damini chopra

||

Answers:

try the below code.

y = ['', '']
if 'Null' in y or '' in y:
    print('nice')
else:
    print('not nice')
Answered By: Karmveer Singh

or evaluates two Boolean expressions. In your case, the statement in the bracket is evaluated first and then the in is evaluated. This leads to the if statement being interpreted as false. You do not need to use the brackets. Just do this:

if 'Null' in y or '' in y:

Now there’s a Boolean expression on either side of the or, so it will evaluate properly.

Answered By: csoham

You can try something like below:

a = ["Hello","","World"]
for words in a:
    if (words):
        print ("Nice")
    else:
        print("Not nice")

Nice
Not nice
Nice
Answered By: Vikash Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.