Python And Or代理..weird [英] Python And Or statements acting ..weird

查看:71
本文介绍了Python And Or代理..weird的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的代码行:

I have this simple line of code:

i = " "

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

这应该很简单,如果我不为空""或它不是空格" ",而是打印东西.现在,如果这两个条件之一是False,为什么我会看到打印的东西?

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?

推荐答案

迪摩根定律

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

这是不可能发生的.因此,无论输入什么内容,(i == "" and i == " ")都将始终返回False,而对其取反将始终给出True.

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.

相反,您应该这样写

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

或根据De Morgan引用的第二条陈述

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

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

这篇关于Python And Or代理..weird的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆