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

如何在Python中基于字典实现州首府用户问答测验

州首府问答程序实现

这个程序会遍历预设的州与首府字典,逐个向用户提问州的首府,判断答案是否正确:

  • 回答正确时,提示用户并加分
  • 回答错误时,告知用户正确答案
  • 全部问题结束后,统计并展示用户最终得分

完整代码

# 预设的州与首府对应字典
statesAndCapitals = {
    "California": "Sacramento",
    "Texas": "Austin",
    "New York": "Albany",
    "Florida": "Tallahassee",
    "Illinois": "Springfield"
}

score = 0
total_questions = len(statesAndCapitals)

# 遍历每个州进行提问
for state, capital in statesAndCapitals.items():
    user_answer = input(f"What is the capital of {state}? ").strip().title()
    
    if user_answer == capital:
        print("Correct!")
        score += 1
    else:
        print(f"Incorrect. The correct answer is {capital}.")

# 输出最终得分
print(f"\nYour final score is {score}/{total_questions}")

关键逻辑说明

  • 用strip()去除用户输入首尾空格,title()将输入转为首字母大写格式,避免因大小写或多余空格导致的误判
  • 初始化score变量记录正确答题数,total_questions获取总题量
  • 遍历statesAndCapitals字典的键值对,逐个发起提问并判断答案
  • 全部问题完成后,输出最终得分

运行效果示例

What is the capital of California? Sacramento
Correct!
What is the capital of Texas? Houston
Incorrect. The correct answer is Austin.
What is the capital of New York? Albany
Correct!
What is the capital of Florida? Miami
Incorrect. The correct answer is Tallahassee.
What is the capital of Illinois? Springfield
Correct!

Your final score is 3/5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:15:48