Python动物猜谜游戏答错自动跳转下一题问题修复求助
问题原因
现有代码的逻辑是无论当前题是否答对,都会直接执行下一题的输入代码,且错误次数是每轮循环强制累加,不是答错才累加,所以会出现答错一次直接跳题的问题,不符合需求。
调整后代码
# 初始化统计变量 wrong_count = 0 score = 0 # 布尔开关:控制是否还有剩余答题机会 has_remaining_chance = True # 统一存储题目和对应正确答案,后续增删题目不用改逻辑,要英文题目直接替换括号里的第一个字符串即可 question_list = [ ("Which bear lives at the North Pole?", "polar bear"), ("Which is the fastest land animal?", "cheetah"), ("Which is the largest animal?", "blue whale") ] print("Guess the Animal\n") for question, right_answer in question_list: # 没机会了直接退出所有答题流程 if not has_remaining_chance: break # 单题循环:答对或者用完机会才会退出当前题 while True: user_guess = input(question).strip().lower() if user_guess == right_answer.lower(): print("Correct Answer") score += 1 break else: wrong_count += 1 # 累计答错3次触发终止逻辑 if wrong_count >= 3: print(f"The Correct answer is {right_answer}") has_remaining_chance = False break print("Sorry Wrong Answer, try again") if not has_remaining_chance: print("You have used up all 3 chances, the program will restart") # 如果需要实际实现重启,可以在这里添加重启逻辑,比如重新执行整个游戏代码块即可 else: print(f"Your Score is {score}")
关键修改说明
- 新增了要求的布尔变量
has_remaining_chance作为全局开关,累计答错3次后开关关闭,直接终止所有答题流程 - 每道题单独做循环控制,只有答对或者用完机会才会进入下一题,不会出现跳题问题
- 只有答错的时候才累加错误次数,符合“总共3次答错机会”的规则
- 题目和答案统一存储在列表中,后续扩展题目不用修改核心逻辑,可维护性更高
内容的提问来源于stack exchange,提问作者Amar Salem
相关产品推荐
相关产品推荐

