Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

Python: and operator doesn't seem to work in while loop

I have code like this

from random import randint
def rand(p):
    a = randint(0, p)
    b = randint(0, p)
    while (a != 501) and (b != 370):
        a = randint(0, p)
        b = randint(0, p)
    print(a, b)
rand(1000)

After some iterations it gets out of the loop, but it doesn't print 501 and 370. It always prints 501 or 370. I have no clue why this is happening. I tried without parentheses in while loop and to put everything in them and It still doesn't seem to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Think about this logically:

  • If a is 501, then a != 501 is False, and False and anything is False, so the whole thing is false and the loop terminates, regardless of the value of b
  • If b is 370, then b != 370 is False, and with the same reasoning, the loop terminates regardless of the value of a

What you're looking for is a != 501 or b != 370:

  • If a is 501, then a != 501 is False, but if b is not 370, then b != 370 is True, meaning the whole thing is True, letting the loop continue
  • Likewise, if b is 370, and a is not 501, the loop continues for the same reasoning
  • If a is 501 and b is 370, you get False or False, which is False, so the loop terminates.

This can also be derived from De Morgan's laws:

  • You want to stop when a == 501 and b == 370, so you loop while not (a == 501 and b == 370)
  • You can apply De Morgan's theorem to "distribute" the not and flip the operation from and to or to get (not (a == 501)) or (not (b == 370))
  • You can replace the ugly not (x == y) with the prettier x != y to get a != 501 or b != 370

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...