试图理解无限条件白循环

2024-04-20 08:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个循环,下面是一个条件的while,我只是想知道为什么它最终是一个无限循环。你知道吗

count = 0            
while count!=12 or count!=6: 
    count = count + 1
    print(count)

Tags: orcount条件printwhile
2条回答

or更改为and,因为您的条件总是True。你知道吗

while count != 12 and count != 6: 

count不能同时是126,因此其中一个表达式将始终为真。你知道吗

这个表达式可以用De Morgan's laws来解释

enter image description here

在Python中,这将是

not (p or q) == (not p) and (not q)

与前面提到的其他方法一样,您需要and而不是or。你知道吗

原因是当循环计数时,您将得到以下结果:

1 != 6 or 12
2 != 6 or 12
...
6 == 6 but != 12 # keeps going
7 != 6 or 12
...
12 != 6 but == 12 # keeps going
...
# infinite loop.

相关问题 更多 >