Python数学测验程序重启功能失效求助
Python数学测验程序重启功能修复方案
原代码存在的问题
calculate函数中return score之后的return check_again()永远无法执行,函数执行第一个return语句后就会终止。check_again函数定义在调用位置之后,Python要求函数必须先定义才能调用。- 重试逻辑仅重复调用
calculate(type),未重新让用户选择运算类型,不符合"重启整个程序"的需求。 - 除法运算时,用户输入的整数会被转为
int类型,而计算结果是float类型,可能导致判断错误或输入非整数答案时程序崩溃。 - 测验结束后未触发
check_again函数,用户看不到重试询问。
修正后的代码
first_number = [50, 48, 8, 12, 16] second_number = [5, 2, 4, 2, 8] num_problems = len(first_number) def check_again(): while True: again = input("\nTry again?(Y/N): ").strip().upper() if again == "Y": return True elif again == "N": return False else: print("请输入Y或N!") def calculate(operation_type): score = 0 for i in range(num_problems): print(first_number[i], end=" ") if operation_type == "Multiplication": print("*", end=" ") correct = first_number[i] * second_number[i] elif operation_type == "Division": print("/", end=" ") correct = first_number[i] / second_number[i] elif operation_type == "Addition": print("+", end=" ") correct = first_number[i] + second_number[i] elif operation_type == "Subtraction": print("-", end=" ") correct = first_number[i] - second_number[i] else: print("无效的运算类型!") return 0 print(second_number[i]) # 处理输入,允许整数或浮点数输入 try: answer = float(input("Enter your answer: ")) except ValueError: print("请输入有效的数字!") print() continue # 用浮点精度判断避免误差 if abs(answer - correct) < 1e-9: print("Correct!") score += 1 else: print(f"Good try! 正确答案是 {correct}") print() return score def run_quiz(): print("Hello and welcome to the Math Quiz!") # 获取运算类型,增加输入校验 while True: operation_type = input("Please select one of the following: Addition, Subtraction, Multiplication, or Division: ").strip() if operation_type in ["Addition", "Subtraction", "Multiplication", "Division"]: break else: print("请输入有效的运算类型!") score = calculate(operation_type) percentage = score * 100 / num_problems print(f"You got a: {percentage}%") if percentage == 100: print("Amazing!") elif percentage == 80: print("Good effort!") elif percentage == 60: print("Keep going!") elif percentage <= 40: print("Better luck next time!") # 主循环,控制测验重启 while True: run_quiz() if not check_again(): break
关键修正说明
- 流程重构:将整个测验逻辑封装到
run_quiz()函数中,通过外层while True循环实现重启功能,用户选择重试时会重新执行完整测验流程(包括重新选择运算类型)。 - 函数顺序调整:将
check_again()和calculate()放在调用之前定义,避免未定义错误。 - 修复无效return:移除
calculate()中无法执行的return check_again(),将重试逻辑移到主循环中统一处理。 - 输入校验增强:
- 运算类型输入增加循环校验,确保用户输入有效选项。
- 答案输入增加
try-except处理,避免非数字输入导致程序崩溃。
- 浮点精度处理:使用
abs(answer - correct) < 1e-9判断答案正确性,避免除法运算中浮点数精度问题导致的判断错误。 - 用户体验优化:优化输入提示格式,对无效输入给出明确提示,重试询问更清晰。
内容的提问来源于stack exchange,提问作者lightlord kaiser
相关产品推荐
相关产品推荐

