Python的“ while”具有两个条件:“和”或“或”

时间:2019-01-12 19:31:52

标签: python while-loop boolean multiple-conditions

这是一个非常简单的骰子掷骰程序,该程序会不断掷骰两个骰子,直到骰子翻倍。所以我的while语句的结构为:

while DieOne != 6 and DieTwo != 6:

由于某种原因,程序DieOne等于6时结束。完全不考虑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

2 个答案:

答案 0 :(得分:0)

TLDR在底部。

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

DieOne != 6 or DieTwo != 6:

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

如果两个条件均成立,运算符将返回true,因此while循环仅在 True和True 时运行。 / p>

所以

while DieOne != 6 and DieTwo != 6:
例如,如果任何一个骰子都掷出6,

就不会运行:

如果DiceOne掷4,而DiceTwo掷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 运算符返回true,因此while循环将在以下情况下运行它是 True或True True或False 或_False或True。 所以

while DieOne != 6 or DieTwo != 6:
如果只有两个骰子掷出六个,

将运行。例如:

如果DiceOne掷4,而DiceTwo掷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

答案 1 :(得分:0)

您需要的是Not而不是!=

尝试一下:

while not (DieOne == 6 or DieTwo == 6):
相关问题