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

如何修改Python测验游戏代码,实现从字典取题并实时验证答案?

Python真假测验游戏修改方案

核心调整方向

将原本分离的题目列表和答案判断逻辑,整合为题目-答案字典,让数据结构更直观,同时简化答案校验的代码逻辑,避免冗余的多条件判断。

具体修改步骤

  • 替换题目存储结构:把原来的questions列表改为字典,键是题目文本,值是对应的正确答案(统一用小写字符串):
    quiz_questions = {
        "Banana is a vegetable": "false",
        "Two plus two equals to four": "true",
        "Mumbai is the capital of present India": "false",
        "Tiger is an example of bird": "false",
        "Punjab is a country": "false"
    }
    
  • 修复用户输入处理bug:原代码中ans1.lower()没有重新赋值,导致输入大小写不生效,改为:
    ans1 = ans1.lower()
    
  • 简化答案判断逻辑:不再通过索引匹配题目,直接从字典中获取当前题目的正确答案,对比用户输入:
    if ans1 == correct_answer:
        points += 1
        print("答对了!")
    else:
        print(f"答错了,正确答案是{correct_answer}")
    
  • 避免重复抽题:原代码用choice可能重复抽取同一题目,改为先将字典转成列表并打乱,再依次遍历:
    question_list = list(quiz_questions.items())
    shuffle(question_list)
    for current_question, correct_answer in question_list:
    

完整优化代码

from random import shuffle

print("""Welcome to the quiz game 
Would you like to play?  """)
consent = input("-----> ").lower()

if consent == "no":
    print("The game ends")
    quit()
else:
    print("Be ready to play")
    print("Answer the questions with 'true' or 'false'")

points = 0
# 用字典存储题目和对应正确答案
quiz_questions = {
    "Banana is a vegetable": "false",
    "Two plus two equals to four": "true",
    "Mumbai is the capital of present India": "false",
    "Tiger is an example of bird": "false",
    "Punjab is a country": "false"
}

# 将题目转成列表并打乱顺序,避免重复出题
question_list = list(quiz_questions.items())
shuffle(question_list)

for current_question, correct_answer in question_list:
    print(f"\nQuestion: {current_question}")
    ans1 = input("(True/False)----> ").lower()
    
    if ans1 == correct_answer:
        points += 1
        print("✅ Correct!")
    else:
        print(f"❌ Wrong! The correct answer is: {correct_answer}")
    
    print(f"Current points: {points}")

print(f"\nGame over! Your final score is: {points}/{len(quiz_questions)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:31:08