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

Python答题程序答错后未终止循环问题排查求助

问题分析

你的代码里,答错时的break语句只跳出了内层遍历答案的for循环,外层的出题循环(遍历随机后的题目)并没有被终止,所以程序会继续出下一题,直到所有题目遍历完。

解决方案

我们可以简化逻辑,直接通过题目索引获取对应答案,去掉冗余的内层循环,同时答错时直接跳出外层的出题循环:

修正后的代码

import random
counter = 0
score = 0

name = input("What is your name?")
print(f"Swagat hai {name} aapka KBC mein!")

questions_list = [
    "Who won the World cup 2022?",
    "The International Literacy day is observed on:", 
    "Bahubali festival is related to:",
    "Which day is observed as the world standards day (Enter month then day)"
]
answer_list = ["Argentina","Sep 8", "Jainism","Oct 14"]

# 生成带索引的题目列表并打乱
idx_question = list(enumerate(questions_list))
random.shuffle(idx_question)

for idxq, question in idx_question:
    print(question)
    ans = input("What is the answer? ")
    
    # 直接通过索引获取对应答案,无需内层循环
    if ans == answer_list[idxq]:
        print("Sahi jawab")
        counter += 1
        score += counter * 10000
    else:
        # 答错直接跳出外层出题循环
        print("Arrey Galat jawab...")
        break

print(f"Aap sirf jeete: {score}")
print("End")

关键修改点

  • 移除冗余内层循环:利用题目索引直接匹配对应答案,避免不必要的遍历
  • 答错时直接终止外层循环:else分支的break会直接停止出题流程,实现答错即退出的需求
  • 优化了字符串拼接方式(用f-string更简洁),移除了无实际作用的incorrect和inputs变量

测试效果

运行后答错任意一题会立即终止程序,示例输出:

What is your name?JIO
Swagat hai JIO aapka KBC mein!
The International Literacy day is observed on:
What is the answer? 12 Jan
Arrey Galat jawab...
Aap sirf jeete: 0
End

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:45:19