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

Python答题游戏while与for循环逻辑错误及答案识别问题求助

答题系统代码修复方案

现有代码问题梳理

  • 修改后的代码没有遍历所有备选答案,直接取列表第一个元组做匹配,导致除了第一个答案的内容外,其余正确答案全部判定为错误
  • 取值逻辑错误:item = possible_answers后取item[0]拿到的是完整答案元组,需要取元组的第一个元素才是答案文本内容
  • 多余的内层while循环无实际作用,外层循环本身已做失误次数校验

正确实现逻辑

每次获取用户输入后,遍历所有备选答案做匹配:

  1. 匹配到对应答案:累加对应分值,本次作答不扣失误次数
  2. 遍历完所有答案都未匹配:判定为答错,扣除1次失误次数

修复后完整代码

question = "Name something a baby does that would be unacceptable in a roommate."
possible_answers = [("CRY/AT 3 A.M.", 39), ("POO/WET SELF", 28), ("PUKE/ON ME", 9), ("BURP", 8), ("MAKE MESS/TOSS FOOD", 5), ("FART", 4), ("PEE IN MY FACE", 3), ("NURSE/ON MY NIPS", 2)]

player_strikes_left = 3
player_score = 0

while player_strikes_left > 0:
    player_answer = input("player answer: ").upper()
    is_correct = False
    earned_points = 0
    # 遍历所有备选答案匹配
    for answer_text, points in possible_answers:
        if player_answer in answer_text:
            is_correct = True
            earned_points = points
            break # 匹配到就跳出,不用继续遍历
    if is_correct:
        print("回答正确")
        player_score += earned_points
    else:
        print("回答错误")
        player_strikes_left -= 1

print(f'最终得分: {player_score}, 剩余失误次数: {player_strikes_left}')

额外优化说明

如果需要避免用户重复答同一个答案重复得分,可以加一个已答对答案的标记列表,每次匹配到后先判断是否已经答过,没答过再加得分,逻辑如下:
初始化加一行answered = [],匹配到正确答案后判断if answer_text not in answered,加分后把answer_text加入answered列表即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:15:05