gpt4 book ai didi

Python And Or 语句表现得很奇怪

转载 作者:行者123 更新时间:2023-11-28 22:38:33 27 4
gpt4 key购买 nike

我有这行简单的代码:

i = " "

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

这应该很简单,如果 i 不是空的 "" 或者它不是空格 "",但它是,打印 Something。现在,如果这 2 个条件之一为 False,为什么我会看到 Something 打印?

最佳答案

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)".

在您的情况下,根据第一条陈述,您已经有效地编写了

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

这是不可能发生的。因此,无论输入是什么,(i == ""and i == "") 将始终返回 False 并将其取反将返回 True 总是。


相反,你应该这样写

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

或根据德摩根定律中引用的第二条陈述,

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

关于Python And Or 语句表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35496768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com