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

如何实现带随机选项的美国总统排序选择题测验?

美国总统任职排序测验代码优化

需求说明

我正在开发一个美国总统排序选择题测验,题目要求从三个选项中选出任职最早的总统。目前已完成无随机功能的循环逻辑,现在引入了数组和随机题目,但需要完善以下内容:

  • 生成不重复的随机选择题选项
  • 实现验证逻辑:当用户输入1、2或3时,程序判断哪个选项在总统列表中的索引最小(即任职最早),验证答案是否正确

原代码

lives = True
import array
import random

print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()

def answer():
if response == presidents

def lifeCount():

    if livesRemaining == 0:
        print("You're out of lives! Good luck trying again!")
        quit()
    
    if livesRemaining == 0:
            quit()

while lives:

    presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
    "Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
    "Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
    "Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]
    
    
    livesRemaining = 3
    
    
    print("Nice to meet you", userName,)
    print("Today you'll be taking a quiz on which U.S President served first out of three options!")
    print("You'll have only three chances to mess up! Let's get started!")
    print("Choose either number 1 2 or 3 on your keyboard!")
    print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents)) 
    
    
    response = input() 
    
    if response == "1":
        print("Correct! 1/10!")  
    else:
        livesRemaining -= 1
        print("Incorrect!")
        lifeCount() 

优化后的代码及说明

import random

# 全局定义总统列表(按任职顺序排列,索引越小任职越早)
presidents = [
    "George Washington", "John Adams", "Thomas Jefferson", "James Maddison", 
    "James Monroe", "John Quincy Adams", "Andrew Jackson", "Martin Van Buren", 
    "William Henry Harrison", "James K. Polk", "Zachary Taylor", "Franklin Pierce", 
    "James Buchanan", "Abraham Lincoln", "Ulysses S. Grant", "Rutherford B. Hayes", 
    "James A. Garfield ", "Grover Cleveland", "Herbert Hoover", "Calvin Coolidge", 
    "Franklin D. Roosevelt", "Harry S. Truman", "Dwight D. Eisenhower", 
    "John F. Kennedy", "Richard Nixon", "Jimmy Carter", "Ronald Reagan", 
    "Bill Clinton", "George W. Bush", "Lyndon B. Johnson"
]

def check_lives(lives_remaining):
    """检查剩余生命数,为0时退出程序"""
    if lives_remaining == 0:
        print("你已经没有生命了!下次加油!")
        quit()

# 初始化游戏
print("欢迎来到Ahmed的美国总统测验!")
print("请输入你的名字:")
user_name = input()
lives_remaining = 3
total_questions = 10
current_question = 0

print(f"很高兴认识你,{user_name}!")
print("今天的测验是从三个选项中选出任职最早的美国总统!")
print("你有3次错误机会,开始吧!")
print("请输入1、2或3来选择选项!")

# 游戏循环
while current_question < total_questions and lives_remaining > 0:
    current_question += 1
    # 生成3个不重复的随机总统选项
    options = random.sample(presidents, 3)
    # 找出选项中任职最早的总统(索引最小的)
    min_index = min(presidents.index(p) for p in options)
    correct_president = presidents[min_index]
    correct_option_num = options.index(correct_president) + 1  # 转成1/2/3的序号
    
    # 显示题目
    print(f"\n第 {current_question}/{total_questions} 题:")
    for i, president in enumerate(options, 1):
        print(f"{i}. {president}")
    
    # 获取用户输入并验证
    while True:
        response = input("请输入你的选择:")
        if response in ["1", "2", "3"]:
            response_num = int(response)
            break
        print("输入无效,请输入1、2或3!")
    
    # 判断答案是否正确
    if response_num == correct_option_num:
        print("回答正确!")
    else:
        lives_remaining -= 1
        print(f"回答错误!正确答案是{correct_option_num}号选项:{correct_president}")
        print(f"剩余生命数:{lives_remaining}")
        check_lives(lives_remaining)

# 游戏结束
if lives_remaining > 0:
    print(f"\n恭喜你完成了所有{total_questions}题!剩余生命数:{lives_remaining}")
else:
    print("\n游戏结束,你用完了所有生命!")

关键优化点

  • 随机选项生成:使用random.sample()确保三个选项不重复,避免出现同一个总统多次出现的情况
  • 验证逻辑实现:通过presidents.index(p)获取每个选项的任职顺序索引,找到最小索引对应的选项即为正确答案,再匹配用户输入的序号
  • 生命管理修复:将lives_remaining初始化移到循环外,避免每次循环重置;重构check_lives函数,逻辑更清晰
  • 输入合法性校验:增加循环确保用户只能输入1、2、3,避免无效输入导致程序出错
  • 题目进度跟踪:添加current_question和total_questions变量,控制测验的总题数,并显示当前进度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:55:45