Python猜谜游戏没有做我想要它做的事情

  • 本文关键字:我想要 游戏 Python python
  • 更新时间 :
  • 英文 :


请原谅我,我是初学者。

这是我的代码的一个简单版本的猜谜游戏。我知道它可以用一种更有效的方式来写,但是请帮助我,让我知道为什么我写的东西不起作用。不管我输入的是什么字母,h还是l,它都会在我选择的第一个字母上循环。

high = 100
low = 0
guess = ((low + high) / 2)
print("Please think of a number between" + str(high) + " and " + str(low))
answer = input("Is your secret number " + str(guess) + "?n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
while guess != 0:
if answer == "h":
high = guess
guess = ((low + high) / 2)
input("Is your secret number " + str(guess) + "?n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
elif answer == "l":
low = guess
guess = ((low + high) / 2)
input("Is your secret number " + str(guess) + "?n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")
elif answer == "c":
print("Game over. Your secret number was " + str(guess))
break
else:
print("Sorry, I did not understand your input."
"Is your secret number " + str(guess) + "?n"
"Enter 'h' to indicate the guess is "
"too high. Enter 'l' to indicate the guess "
"is too low. Enter 'c' to indicate I "
"guessed correctly.")

您需要将answer = input("Is your secret number ...")行放入while循环中,以便每次程序都获得新的输入。这将是:

...
while guess != 0:
answer = input("Is your secret number ...")
if answer == 'h':
...

我还建议您使用f-string来打印数字,所以不要使用:

print("Please think of a number between" + str(high) + " and " + str(low))

你可以直接写:

print(f"Please think of a number between {high} and {low}")

要了解更多关于f-string的信息,请查看此页。

相关内容

  • 没有找到相关文章