我以前使用過 while 回圈等,但這個回圈根本無法達到中斷條件。這個游戲是關于在盒子里尋找隱藏的東西。我已經添加了一些實際游戲中不會出現的代碼,以幫助我驗證隱藏的是哪個盒子。盒子的范圍是從 1 到 5,并且每次游戲重新開始時都是隨機的。我已經開始將猜測框設為假,因為我需要一些東西來填充空間并將 in_box 變成一個字串以防萬一。
from random import randrange
in_box = randrange(1, 5)
str(in_box)
guess_box = False
print("To guess which box enter in the numbers that each box relates to, eg, Box 1 will be the number 1! Ready? Set? Go!")
while guess_box != in_box:
print(f"I was in box {in_box}")
guess_box = input("Which box? ")
if guess_box == in_box:
print("Great job, you found me!")
break
else:
print("I'm still hiding!!")
print("Thank you for playing")
uj5u.com熱心網友回復:
您將 in_box 設定為字串而不是保存它。你需要做in_box=str(in_box):
from random import randrange
in_box = randrange(1, 5)
in_box = str(in_box)
guess_box = False
print("To guess which box enter in the numbers that each box relates to, eg, Box 1 will be the number 1! Ready? Set? Go!")
while guess_box != in_box:
print(f"I was in box {in_box}")
guess_box = input("Which box? ")
if guess_box == in_box:
print("Great job, you found me!")
break
else:
print("I'm still hiding!!")
print("Thank you for playing")
沒有這個,就永遠不會滿足打破回圈的條件。
uj5u.com熱心網友回復:
您需要將輸入轉換為整數型別,input() 的默認型別是 str。
結果是類似 '1' == 1 的邏輯,這是錯誤的所以條件永遠不會通過。
from random import randrange
in_box = randrange(1, 5)
str(in_box)
guess_box = False
print("To guess which box enter in the numbers that each box relates to, eg, Box 1 will be the number 1! Ready? Set? Go!")
while guess_box != in_box:
print(f"I was in box {in_box}")
guess_box = input("Which box? ")
if int(guess_box) == in_box:
print("Great job, you found me!")
break
else:
print("I'm still hiding!!")
print("Thank you for playing")
作業,注意 int() 在 if 條件下的猜測框周圍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/329734.html
