【发布时间】:2022-08-17 18:03:08
【问题描述】:
我是初学者,所以如果这是一个愚蠢的问题,请原谅我。我写了这个猜谜游戏(使用教程),用户选择一个上限,然后选择一个随机数作为“秘密数字”。
当用户猜测并且它低于/高于秘密数字时,下限/上限会改变以给用户一个提示。例如,密码为 50。用户输入 30。下限从 0 变为 30。
在下一次尝试中,如果用户键入低于 30 的数字,则下限会降低。例如,在第二次尝试中,用户写入 20。在第三次尝试中,下限现在为 20。
我不知道如何阻止这种情况发生。我希望程序告诉用户他们不能低于/高于他们在上一次尝试中猜测的数字,而不是改变下限。
这是代码:
import random
while True:
flag=True
while flag:
num = input(\"Choose an upper bound: \")
if num.isdigit():
print(\"Let\'s play!\")
num=int(num)
flag=False
else:
print(\"Invalid input. Try again: \")
secret_number = random.randint(1, num)
no_tries=0
max_tries=3
lower_limit=0
upper_limit=num ```
while no_tries<max_tries:
guess = int(input(f\"Please type a number between {lower_limit} and {upper_limit} \"))
no_tries=no_tries+1
if guess==secret_number:
print(\"You won!\")
break
elif guess<secret_number:
print(f\"You\'ve guessed wrong.\")
lower_limit=guess
elif guess>secret_number:
print(f\"You\'ve guessed wrong.\")
upper_limit=guess
else:
print(\"You have used all three tries. You lose!\")
user_input=input(\"Would you like to play again? Y/N: \").upper()
if user_input==\"N\":
print(\"Game over\")
break
-
添加额外的比较。仅当
lower_limit小于guess时才执行lower_limit=guess。
标签: python