You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜数字游戏运行无响应,请求重写完整可运行代码

修复后的数字匹配游戏代码

先梳理原代码存在的核心问题:

  • main()函数结构错误,无法触发执行
  • random.randint()参数使用错误
  • 输入合法性判断逻辑完全错误
  • 类的初始化参数冗余,且未调用核心方法

以下是完整可运行的代码:

import random

class Game():
    def __init__(self):
        # 初始化时仅定义属性,后续方法赋值
        self.computer_choice = None
        self.user_choice = None

    def generate_computer_choice(self):
        # 生成0-10范围内的随机整数(包含0和10)
        self.computer_choice = random.randint(0, 10)

    def get_user_choice(self):
        # 获取用户输入并做合法性校验
        while True:
            try:
                user_input = int(input("请输入一个0-10范围内的数字:"))
                if 0 <= user_input <= 10:
                    self.user_choice = user_input
                    break
                else:
                    print("输入无效,请输入0到10之间的数字!")
            except ValueError:
                print("输入无效,请输入整数!")

    def judge_result(self):
        # 判断胜负
        if self.computer_choice == self.user_choice:
            print(f"恭喜你获胜!电脑选的数字是{self.computer_choice}")
        else:
            print(f"很遗憾你输了!电脑选的数字是{self.computer_choice}")

def main():
    game = Game()
    game.generate_computer_choice()
    game.get_user_choice()
    game.judge_result()

if __name__ == "__main__":
    main()

关键修改说明

  • 重构Game类初始化逻辑,去掉冗余参数,改为初始化时定义属性为None
  • 修正random.randint()用法,传入0和10作为范围边界,符合题目要求的0-10范围
  • 优化用户输入处理,通过循环+异常处理确保输入是0-10之间的整数
  • 修正main()函数结构,正确实例化Game类并调用核心方法
  • 重命名方法名使其更具可读性(比如computer()改为generate_computer_choice())

内容的提问来源于stack exchange,提问作者Sa.m.ue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 07:31:05