pythonpython-3.xlogical-operatorsdemorgans-law

Python And Or statements acting ..weird


I have this simple line of code:

i = " "

if i != "" or i != " ":
    print("Something")

This should be simple, if i is not empty "" OR it's not a space " ", but it is, print Something. Now, why I see Something printed if one of those 2 conditions is False?


Solution

  • De Morgan's laws,

    "not (A and B)" is the same as "(not A) or (not B)"
    
    also,
    
    "not (A or B)" is the same as "(not A) and (not B)".
    

    In your case, as per the first statement, you have effectively written

    if not (i == "" and i == " "):
    

    which is not possible to occur. So whatever may be the input, (i == "" and i == " ") will always return False and negating it will give True always.


    Instead, you should have written it like this

    if i != "" and i != " ":
    

    or as per the quoted second statement from the De Morgan's law,

    if not (i == "" or i == " "):