Python And Or statements acting ..weird

2020-02-07 05:01发布

问题:

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?

回答1:

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


回答2:

This condition:

if i != "" or i != " ":

will always be true. You probably want and instead of or...



回答3:

I will explain how or works.
If checks the first condition and if it is true it does not even check for the second condition.
If the first condition is false only then it checks for second condition and if it is true the whole thing becomes true.
Because

A B Result  
0 0   0  
0 1   1  
1 0   1  
1 1   1  

So If you want to satisfy both condition of not empty and space use and



回答4:

Your print statement will always happen, because your logic statement is always going to be True.
if A or B:
will be True if either A is True OR B is True OR both are True. Because of the way you've written the statement, one of the two will always be True. More precisely, with your statement as written, the if statement correlates to if True or False: which simplifies to if True:.
It seems that you want an and statement instead of an or.



回答5:

i = " "

you have the condition as

if i != "" or i != " ":

here i != "" will evaluate to True and i != " " will evaluate to False

so you will have True or False = True

you can refer this truth table for OR here

True  or False = True
False or True  = True
True  or True  = True
False or False = False