3

我有以下用 Python 编写的代码作为项目。我已将计算机科学作为 GCSE。我对它很陌生,所以不知道如何修复这个错误。当我输入我的第一个猜测时,例如“5”,它会显示太高。然后一旦游戏完成,它会说答案是7。这是一个我不断尝试解决但无法完成的错误。这是我使用的代码:

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

while numberofGuesses < 3: 
    numberofGuesses = numberofGuesses +1 
    randomNumber = (random.randint(1,10)) 
    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!")`

除了我提到的一个错误之外,此代码可以完美运行。

4

3 回答 3

7

每次猜测时,您都在重新选择一个随机数。相反,我相信您希望程序先选择一个数字,然后进入您的 while 循环。

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

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")
于 2013-10-24T19:36:55.427 回答
3

除了在每次迭代中重置随机数之外,还有另一个问题:

如果猜测正确,您不会停止循环。并且您应该在猜测评估后增加猜测计数器,否则您将无法判断有人在第三次尝试时是否正确猜测:

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!")
于 2013-10-24T19:46:40.113 回答
1

您将 randomNumber 设置为每次猜测的新随机数 - 所以对于第一个答案,它可能是 7,然后您进行猜测,它会更改为 3。要解决此问题,请移出randomNumber = (random.randint(1,10))while 循环 - 执行此操作一次,而不是每次猜测一次。干杯,祝你学习顺利!

于 2013-10-24T19:38:07.220 回答