[英]While or loop not stopping after set integer in python
嘗試與精通計算機的玩家一起制作石頭剪刀布游戲以更新編碼知識,但是我似乎無法在我的 while 循環中找到導致問題的原因。 我將它設置為在計算機或人達到 3 分時完成,但在總分等於 8 時停止。下面列出了完整代碼
import random
rock = "rock"
paper = "paper"
scissors = "scissors"
humanscore = int(0)
compscore = int(0)
limit = int(3)
comp = ["paper", "rock", "scissors"]
while humanscore <= limit or compscore <= limit:
human = str(input("Choose rock, paper, or scissors, first to 3 wins! "))
answer = random.choice(comp)
if human == answer:
print("Tie, Computer chose, ", answer)
if answer == rock:
if human == paper:
humanscore += 1
print("You Win!")
elif human == scissors:
compscore += 1
print("Computer Won! Try again")
if answer == paper:
if human == rock:
compscore += 1
print("Computer Won! Try again")
elif human == scissors:
humanscore + 1
print("You Win!")
if answer == scissors:
if human == paper:
compscore += 1
print("Computer Won! Try again")
elif human == rock:
humanscore += 1
print("You Win!")
print("\n Computer Chose: ", answer, "computer score: ", compscore, "Human Score:", humanscore)
正如評論中已經說過的or
,問題出在您的休息條件下。 只要其中一個分數低於或等於 3,它就會繼續運行。
例如,如果humanscore = 3 和comp score = 2,則條件的兩個部分都是真實的,這意味着它會繼續。
一旦humanscore = 4 和compscore = 4,humanscore <= 3 和compscore <= 3 都評估為false,這意味着它停止=> 總分為8。
因此,while 應該如下所示(也應該是<
而不是<=
,因為你想在一個有 3 個點時立即停止):
while humanscore < limit and compscore < limit:
一旦你理清了循環——如果你只想在分數都低於limit
的情況下繼續前進,根據 schilli 的回答進行更正——你可能想考慮一個數據結構建議:
制作一個記錄什么選擇勝過給定選擇的dict
:
whatBeats = {rock:paper, paper:scissors, scissors:rock}
# then later after choices are made...
if answer == whatBeats[human]:
# computer win
elif human == whatBeats[answer]:
# human win
else:
# draw
(幾十年前,我在了解任何索引結構之前編寫了一個排序程序——比如 arrays——你當前的方法讓我想起了那種努力)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.