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

Python编写的测验程序输入一次答案就匹配所有问题如何解决

代码问题说明
  • 输入调用位置错误:input() 放置在循环外部,仅会触发一次用户输入,因此只会拿到一次答案用于所有题目匹配
  • 分支判断逻辑无效:if [0]、if [1]、if [2] 为错误写法,Python中非空列表的布尔值恒为True,每次循环都会执行全部三道题的校验逻辑
  • 等值判断语法错误:answer == "Phoenix" or "phoenix" 不符合语法规则,非空字符串"phoenix"的布尔值恒为True,无论用户输入什么都会被判定为正确
  • 题目答案无对应关系:随机抽题后未记录选中的题目索引,无法匹配对应正确答案
修复后可运行代码
import random
score = 0
# 整理题目与对应正确答案,统一转小写方便后续大小写不敏感校验
quiz_bank = [
    {"question": "What is the capital of Arizona: ", "correct_ans": "phoenix"},
    {"question": "What thing in Arizona is a part of the 7 natural wonders of the world (ABRIVEATE ANSWER TO THE 1ST LETTER OF EACH WORD):  ", "correct_ans": "tgc"},
    {"question": "what is the timezone in Arizona: ", "correct_ans": "gmt"}
]

# 打乱题目顺序,实现随机抽题效果
random.shuffle(quiz_bank)

for quiz in quiz_bank:
    # 每次循环都触发一次输入,同时去除首尾空格、转小写,兼容大小写和误输空格
    user_input = input(quiz["question"]).strip().lower()
    if user_input == quiz["correct_ans"]:
        print("Correct")
        score += 1
    else:
        print("Incorrect")
    print(f"当前得分:{score}")

print(f"测验结束,最终得分:{score}")

内容的提问来源于stack exchange,提问作者ZDilly Da Silly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:39:04