Python And Or statements acting ..weird

*爱你&永不变心* 提交于 2019-11-28 14:15:47

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

This condition:

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

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

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

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!