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

为何break语句无法退出try循环?Python数学答题程序故障排查

Python数学答题程序问题修复

问题说明

当前程序功能:用户输入1-3级难度(对应算式数字位数),完成加法答题。答错输出EEE,首次答对退出函数并使total_correct_answers加1,弹出新题目。但存在以下问题:

  • 用户先答错再答对时,同一题目反复弹出,循环未正常退出
  • total_correct_answers计数逻辑错误,无法正确统计答对数量

原代码

import random

def main():
    ten_questions()

def get_level():
    while True:
        try:
            level_input = int(input("Level: "))
            if level_input in [1,2,3]:
                return level_input
        except:
            pass

def integer_generator(level):
    if level == 1:
        x = random.randint(0,9)
        y = random.randint(0,9)
    elif level == 2:
        x = random.randint(10, 99)
        y = random.randint(10, 99)
    else:
        x = random.randint(100, 999)
        y = random.randint(100, 999)
    return x, y

def question_generator(x, y):
    real_answer = x + y
    wrong_counter = 0
    while True:
        try:
            answer_given =  input(str(x) + " + " + str(y) + " = ")
            if int(answer_given) == real_answer:
                if wrong_counter == 0:
                    return True
            elif int(answer_given) == real_answer and wrong_counter != 0:
                break
            else:
                while wrong_counter < 2:
                    print("EEE")
                    wrong_counter +=1
                    break
                else:
                    print(str(x) + " + " + str(y) + " = " + str(real_answer))
                    print("False, that was last attempt")
                    break

        except:
            print("EEE")
            pass

def ten_questions():
    num_of_questions = 0
    total_correct_answers = 1
    my_level = get_level()
    correct_answers = question_generator(*integer_generator(my_level))
    while num_of_questions <= 8:
        question_generator(*integer_generator(my_level))
        num_of_questions +=1
        if correct_answers == True:
            total_correct_answers +=1
    print("Score: " + str(total_correct_answers))

if __name__ == "__main__":
    main()

问题分析

  1. question_generator逻辑混乱:
    • 答对判断分支冗余,elif int(answer_given) == real_answer永远不会触发,导致答错后再答对时循环无法退出
    • 错误计数使用嵌套while循环,逻辑错误,无法正确累计错误次数
    • 仅首次答对返回True,后续答对无返回值,函数无法正常退出
  2. ten_questions计数错误:
    • 仅初始化时调用一次question_generator并赋值,后续循环的调用结果未接收,导致计数仅执行一次
    • total_correct_answers初始值设为1,不符合计数逻辑,应从0开始

修复后的代码

import random

def main():
    ten_questions()

def get_level():
    while True:
        try:
            level_input = int(input("Level: "))
            if level_input in [1, 2, 3]:
                return level_input
        except ValueError:
            pass

def integer_generator(level):
    if level == 1:
        x = random.randint(0, 9)
        y = random.randint(0, 9)
    elif level == 2:
        x = random.randint(10, 99)
        y = random.randint(10, 99)
    else:
        x = random.randint(100, 999)
        y = random.randint(100, 999)
    return x, y

def question_generator(x, y):
    real_answer = x + y
    wrong_counter = 0
    while True:
        try:
            answer_given = input(f"{x} + {y} = ")
            user_answer = int(answer_given)
            if user_answer == real_answer:
                # 无论是否答错,答对都返回True
                return True
            else:
                wrong_counter += 1
                print("EEE")
                if wrong_counter >= 3:
                    print(f"{x} + {y} = {real_answer}")
                    print("False, that was last attempt")
                    return False
        except ValueError:
            # 输入非数字时也计数错误
            wrong_counter += 1
            print("EEE")
            if wrong_counter >= 3:
                print(f"{x} + {y} = {real_answer}")
                print("False, that was last attempt")
                return False

def ten_questions():
    total_correct_answers = 0
    my_level = get_level()
    # 循环生成10道题
    for _ in range(10):
        x, y = integer_generator(my_level)
        if question_generator(x, y):
            total_correct_answers += 1
    print(f"Score: {total_correct_answers}")

if __name__ == "__main__":
    main()

修复说明

  • question_generator优化:
    • 简化答对判断,只要答对就返回True,确保循环退出
    • 错误计数改为线性逻辑,累计到3次时显示正确答案并返回False
    • 输入非数字时也累计错误次数,避免无限输入无效内容
  • ten_questions优化:
    • 初始化total_correct_answers为0,符合计数逻辑
    • 使用for循环生成10道题,每道题的答题结果直接用于计数
    • 格式化字符串替代拼接,代码更简洁

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:54:18