修复 Python 猜数字游戏中的错误

110 阅读2分钟

一位学习计算机科学课程的 Python 初学者遇到了一个问题,他在编写一个猜数字游戏时,遇到了一个游戏逻辑错误。每当他输入第一个猜测,例如 5,游戏会提示“ 太低了”。但当游戏结束后,游戏会说答案是 7。他多次尝试解决这个问题,但始终未能解决。他找到了解决方法,但还需要调整代码,以便游戏能够正常运行。

2、解决方案

huake_00183_.jpg

第一个回答者指出了错误的原因:游戏在每次猜测时都会重新选择一个随机数。他建议将 randomNumber = (random.randint(1,10)) 移出 while 循环,这样游戏只需要选择一次随机数,而不是每次猜测都选择一次。这是修改后的代码:

import random

numberofGuesses = 0
randomNumber = (random.randint(1,10))

print("I'm thinking of a number between 1 and 10. What is it? You have three guesses.")

while numberofGuesses < 3:
    numberofGuesses = numberofGuesses +1

    userInput = 0
    userInput = input ()
    userInput = int(userInput)

    if randomNumber > userInput:
        print("Too Low! Try again")
    if randomNumber < userInput:
        print("Too High! Try Again")

if numberofGuesses == 3:
    print("Sorry! You lose. The correct number was:",randomNumber)

if randomNumber == userInput:
    print("Well Done! Your guess was correct!")

答案 2:

第二个回答者指出了另一个问题:游戏没有在猜对时停止循环。并且建议在对猜测进行评估后增加猜测计数器,否则无法判断某人在第三次尝试时是否猜对了。这是修改后的代码:

import random

numberofGuesses = 0
randomNumber = (random.randint(1,10))

print("I'm thinking of a number between 1 and 10. What is it? You have three guesses.")

while numberofGuesses < 3:
    userInput = int(input())

    if randomNumber > userInput:
        print("Too Low! Try again")
    elif randomNumber < userInput:
        print("Too High! Try Again")
    else:  # Correct guess!
        break

    numberofGuesses = numberofGuesses +1

else:  # Executed only if the while loop is not exited via "break"
    print("Sorry! You lose. The correct number was:",randomNumber)

if randomNumber == userInput:
    print("Well Done! Your guess was correct!")

答案 3:

第三个回答者也指出了同样的错误:每次猜测都会重新生成一个随机数。他建议将 randomNumber = (random.randint(1,10)) 移出 while 循环,这样游戏只需要选择一次随机数。这是修改后的代码:

import random

numberofGuesses = 0

randomNumber = (random.randint(1,10))

print("I'm thinking of a number between 1 and 10. What is it? You have three guesses.")

while numberofGuesses < 3:
    userInput = 0
    userInput = input ()
    userInput = int(userInput)

    if randomNumber > userInput:
        print("Too Low! Try again")
    if randomNumber < userInput:
        print("Too High! Try Again")

    numberofGuesses = numberofGuesses +1

if numberofGuesses == 3:
    print("Sorry! You lose. The correct number was:",randomNumber)

if randomNumber == userInput:
    print("Well Done! Your guess was correct!")

经过上述修改,游戏应该能够正常运行。修复了游戏逻辑错误,现在游戏会根据玩家的猜测做出正确的提示,并最终确定玩家是否猜对了。