[英]Python 'while' with two conditions: "and" or "or"
這是一個非常簡單的擲骰子程序,它不斷擲出兩個骰子,直到得到雙六。 所以我的 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
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 為真,而 DieTwo != 6 為假。 我把這個思路放到了下面的代碼中。
while DieOne != 6 and DieTwo != 6:
while True and False:
while False: #So it won't run because it is false
or運算符的工作方式不同, or運算符在其中一個條件為真時返回真,因此 while 循環將在它為True 或 True 、 True 或 False或 _False 或 True 時運行。 所以
while DieOne != 6 or DieTwo != 6:
如果只有兩個骰子擲出 6,則將運行。 例如:
如果 DieOne 擲出 4 而 DieTwo 擲出 6,while 循環將運行,因為 DieOne != 6 為真,而 DieTwo != 6 為假。 我把這個思路放到了下面的代碼中。
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
你需要的是Not
而不是!=
。
嘗試這個:
while not (DieOne == 6 or DieTwo == 6):
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
唔。 基於多個條件,將其歸結為單個條件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!
"""
感覺像是多個條件都被打破了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.