Python And Or statements acting ..weird

随声附和 提交于 2019-12-17 21:10:46

问题


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


来源:https://stackoverflow.com/questions/35496768/python-and-or-statements-acting-weird

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