CS50P作业4:Little Professor程序check50测试失败求助
CS50 Little Professor check50测试失败的解决方法
你的check50测试出现"Level: X + Y ="或"Level: EEE"这类错误,核心问题在于原代码中finally块的逻辑存在执行时机隐患,同时在管道输入的测试场景下,input提示和程序输出被误判为同一行内容。
修改方案
移除finally块,将三次尝试失败后打印正确答案的逻辑移到while循环外部,简化错误处理流程,确保输出格式完全符合作业要求:
import random def main(): level = get_level() score = 0 for _ in range(10): x = generate_integer(level) y = generate_integer(level) correct = x + y attempts = 3 while attempts > 0: try: answer = int(input(f"{x} + {y} = ")) if answer == correct: score += 1 break else: attempts -= 1 if attempts > 0: print("EEE") except ValueError: attempts -= 1 if attempts > 0: print("EEE") if attempts == 0: print(f"{x} + {y} = {correct}") print(f"Score: {score}") def get_level(): while True: try: level = int(input("Level: ").strip()) if level in (1, 2, 3): return level except ValueError: pass def generate_integer(level): if level == 1: return random.randint(0, 9) elif level == 2: return random.randint(10, 99) elif level == 3: return random.randint(100, 999) else: raise ValueError if __name__ == "__main__": main()
修改说明
- 移除
finally块:原代码中finally会在每次try/except执行后触发,可能导致不必要的代码执行,现在将正确答案的打印逻辑移到while循环结束后,仅当三次尝试全部失败时执行。 - 简化错误处理:明确仅在还有剩余尝试次数时输出"EEE",避免多余输出。
- 优化变量命名:使用更直观的变量名,提升代码可读性。
内容的提问来源于stack exchange,提问作者Nowhere Man
相关产品推荐
相关产品推荐

