我应该使用“和”或“或”中的哪一个来加入非相等性检查,为什么?

问题描述 投票:0回答:4

这是一个非常简单的掷骰子程序,不断掷两个骰子,直到得到双六。所以我的 while 语句的结构如下:

while DieOne != 6 and DieTwo != 6:

出于某种原因,一旦

DieOne
获得六分,该计划就会结束。
DieTwo
根本不考虑。

但是,如果我在 while 语句中将

and
更改为
or
,则程序可以完美运行。这对我来说没有意义。

import random
print('How many times before double 6s?')
num=0
DieOne = 0
DieTwo = 0

while DieOne != 6 or DieTwo != 6:
    num = num + 1
    DieOne = random.randint(1,6)
    DieTwo = random.randint(1,6)
    print(DieOne)
    print(DieTwo)
    print()
    if (DieOne == 6) and (DieTwo == 6):
        num = str(num)
        print('You got double 6s in ' + num + ' tries!')
        print()
        break
python while-loop boolean multiple-conditions
4个回答
17
投票

TLDR 在底部。

首先,如果以下条件为真,则 while 循环运行,所以

DieOne != 6 or DieTwo != 6:

简化后必须返回 true,以便 while 函数运行

如果两个条件都为真,则and运算符返回true,因此while循环仅在True且True时运行。

因此,如果任一骰子掷出 6,则以下代码将不会运行:

while DieOne != 6 and DieTwo != 6:

如果 DieOne 掷出 4 并且 DieTwo 掷出 6,则 while 循环将不会运行,因为 DieOne != 6 为 true,而 DieTwo != 6 为 false。我把这个思路写进了下面的代码中。

while DieOne != 6 and DieTwo != 6:
while True and False:
while False: #So it won't run because it is false

or运算符的工作方式不同,当one条件为真时,or运算符返回true,因此当它为True或TrueTrue或False、或_False或时,while循环将运行真的。 所以

while DieOne != 6 or DieTwo != 6:

如果只有一个骰子掷出 6,则运行。例如:

如果 DieOne 掷出 4 并且 DieTwo 掷出 6,则 while 循环将运行,因为 DieOne != 6 为 true,而 DieTwo != 6 为 false。我把这个思路写进了下面的代码中。

while DieOne != 6 or DieTwo != 6:
while True or False:
while True: #So it will run because it is true

TLDR/评论:

while True: #Will run
while False: #Won't run

并且:

while True and True: #Will run
while True and False: #Won't run
while False and True: #Won't run
while False and False: #Won't run

或者:

while True or True: #Will run
while True or False: #Will run
while False or True: #Will run
while False or False: #Won't run

3
投票

您需要的是

Not
而不是
!=

试试这个:

while not (DieOne == 6 or DieTwo == 6):

0
投票
while DieOne != 6:
   if DieTwo != 6:
      break
   num = num + 1
   DieOne = random.randint(1, 6)
   DieTwo = random.randint(1, 6)
   print(DieOne)
   print(DieTwo)
   print()
   if (DieOne == 6) and (DieTwo == 6):
      num = str(num)
      print('You got double 6s in ' + num + ' tries!')
      print()
      break

0
投票

嗯。基于多个条件,将其归结为单个条件,

both_6:bool

import random

num = 0
both_6 = False

​
while not both_6:
    num += 1

    DieOne = random.randint(1,6)
    DieTwo = random.randint(1,6)

    if (DieOne==6) and (DieTwo==6):
        both_6 = True
        print(f"\nIt took you {num} attempts to get double sixes!\n")


"""
It took you 25 attempts to get double sixes!
"""

感觉多个条件被打破了

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.