tangguo

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.")

阅读 132

收藏
2022-06-13

共1个答案

小编典典

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

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

我还建议您使用 f-strings 打印出数字,而不是:

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

你可以写:

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