我以前使用过while循环和类似的循环,但是这个循环根本不会达到中断的条件。这个游戏是关于寻找隐藏在盒子里的东西。我添加了一些代码,这些代码在实际游戏中是不会出现的,这可以帮助我验证哪个盒子被隐藏了。盒子的范围从1到5不等,每次游戏重新开始时都是随机的。我一开始把guess-box设置为false,因为我需要一些东西来填充空格,为了以防万一,我把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")
您将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")
如果没有这个,就永远不会满足终止循环的条件。
您需要将输入强制转换为整数类型,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")
可以工作,注意在if条件中int()绕过guess-box。