Python "equal to" 和 "not equal to"

Python "equal to" and "not equal to"

我正在做一道练习题,但无法弄清楚自己做错了什么。似乎我对 or 应该如何工作有点困惑。

我将传递 13 - 19 的两个数字范围:

for i in range(13,20):
    func(i)

Function 1

def func(n):
    if n == 15 or n == 16:
        pass
    else:
        n = 0

Result 1

0
0
15
16
0
0
0

因此,如果 n 等于 15 或者如果 n 等于 16,则通过。其他任何东西,将其设为 0。有道理。

Function 2

def func(n):
    if n != 15 and n != 16:
        n = 0
    else:
        pass

Result 2

0
0
15
16
0
0
0

如果n不等于15或16,则将其设为0。否则,通过。同样,有道理。

这是我有点松懈的地方:

Function 3

def func(n):
    if n == 15 and n == 16:
        pass
    else:
        n = 0

Result 3

0
0
0
0
0
0
0

我认为结果是因为n的两个条件都需要满足;如果等于 15 16,则通过,否则将其设为零。我明白了。

Function 4

def func(n):
    if n != 15 or n != 16:
        n = 0
    else:
        pass

Result 4

0
0
0
0
0
0
0

如果n不等于15或n不等于16,那么它应该是零。

我认为 这意味着 or 在某种程度上与 and 的工作方式相同,因为必须满足这两个条件,但想知道是否有人更有知识可以解释一下吗?

这基本上就是De-Morgan规律。

~(a and b) = (~a or ~b).

if n != 15 or n != 16:

每个数字(包括 15 和 16)都通过了这个测试,所以结果总是 True。请记住,只有一个条件需要 True 才能使 or 语句评估为 True。每个数字要么不等于 15 ,要么 不等于 16.


I think this means or somehow works the same way as and in that both conditions must be met, but was wondering if someone more knowledgeable could explain?

通常情况并非如此。您已经编写了一个特例,其中 ornot 的行为类似于 and。 (参见 Maged 关于 DeMorgan 定律 的回答)