python - 猜游戏错误?

标签 python

我有以下用 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!")`

除了我提到的一个错误之外,这段代码工作完美。

最佳答案

每次猜测时,您都在重新选择一个随机数。相反,我相信您希望程序先选择一个数字,然后输入您的 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")

关于python - 猜游戏错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19574998/

相关文章:

python - 为什么这个循环返回两次?

python - 在 Django 模板中检查一个或多个回发的正确方法是什么?

python - 拟合模型时出现 ValueError

python - 为什么不建议在conda基础环境中安装额外的包?它的目的是什么?

python - 如何求解投资组合优化的方程组和约束条件?

Python - 检查文件名的扩展名

python - 按照教程进行:无法运行Django的Docker容器

python - 如何关闭(或隐藏)openpyxl 组合图表上的秒 y 轴刻度?

python - 如何从 Python 中的线程获取返回值?

python - boto3 S3 对象解析