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

Python初学者写的数学答题游戏代码无报错但不存分还卡顿如何解决

问题原因和修改方案

你的代码存在以下几处核心逻辑错误,导致无法正常保存分数:

  • 排名计算逻辑位置错误:插入分数、姓名的代码被放在了遍历历史分数的for循环内部,既会导致重复插入无效数据,当没有历史分数(第一次运行)时,for循环完全不执行,新的分数和姓名根本不会被存入列表。需要先遍历所有历史分数算出最终排名位置,再执行一次插入操作。
  • 写入文件类型不匹配:scores[pos]是整数格式,不能直接和字符串拼接,且写入时没有加换行符,会导致后续读取无法正确分割每行数据。
  • 文件操作不完整:写入文件完成后没有调用close()方法,内存中的数据不会刷入磁盘,导致文件看起来没有写入内容。
  • 历史数据重复累加:scores和names列表定义在循环外,每次循环读取历史分数时直接append,多次运行后会出现大量重复数据。
  • 无效读取操作:遍历文件内容后文件指针已经在末尾,后续print(f.read())读不到任何内容,可以直接删除。
修复后的代码
while True:
    # 每次循环前先清空历史列表,避免重复累加
    scores = []
    names = []
    # 兼容首次运行没有高分文件的情况
    try:
        f = open("highscore.txt", "r")
        for line in f:
            line = line.strip("\n")
            line = line.split(" ")
            names.append(line[0])
            scores.append(int(line[1]))
        f.close()
    except FileNotFoundError:
        # 首次运行没有文件时直接用空列表
        pass
    
    # 打印历史排名
    print("当前排行榜:")
    for pos in range(len(names)):
        print(pos + 1, names[pos], scores[pos])

    score = 0
    print("hello, welcome to maths game")
    print("\nQuestion 1: what is 2 x 2 x 2?")
    answer = int(input("your answer >"))
    if answer == 8:
        print("correct")
        score = score + 1
        print("your score is ", score)
    else:
        print("incorrect")
        print("the score is ", score)

    print("\nQuestion 2: what is 34 x 2?")
    answer = int(input("your answer >"))
    if answer == 68:
        print("correct")
        score = score + 1
        print("your score is", score)
    else:
        print("incorrect")
        print("the score is", score)

    name = input("what is your name?")
    position = 0
    # 先遍历所有分数算出最终排名
    for compare_score in scores:
        if score < compare_score:
            position = position + 1
    # 循环结束后再插入一次
    scores.insert(position, score)
    names.insert(position, name)
    # 只保留前5名
    scores = scores[:5]
    names = names[:5]

    # 写入高分文件
    f = open("highscore.txt", "w")
    for pos in range(len(names)):
        # 转成字符串+加换行符
        f.write(f"{names[pos]} {scores[pos]}\n")
    # 关闭文件确保数据写入磁盘
    f.close()

内容的提问来源于stack exchange,提问作者S. Tack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:03