Python And Or statements acting ..weird

前端 未结 5 1437
盖世英雄少女心
盖世英雄少女心 2020-12-07 04:30

I have this simple line of code:

i = \" \"

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

This should be simple, if i is not empty <

5条回答
  •  伪装坚强ぢ
    2020-12-07 05:15

    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 == " "):
    

提交回复
热议问题