欢迎访问宙启技术站
智能推送

使用prompt()函数实现一个简单的选择题游戏(Python)

发布时间:2023-12-14 06:48:01

使用prompt()函数可以实现一个简单的选择题游戏。下面是一个示例代码:

def show_question(question, choices):
    print(question)
    for i, choice in enumerate(choices):
        print(f"{i+1}. {choice}")

def get_user_choice(choices):
    while True:
        choice = input("请输入您的选择:")
        if choice.isdigit() and int(choice) in range(1, len(choices)+1):
            return int(choice)
        else:
            print("请输入有效的选择数字。")

def play_game():
    questions = [
        {
            "question": "下面哪个不是Python的基本数据类型?",
            "choices": ["int", "bool", "list", "str"],
            "correct_answer": 3
        },
        {
            "question": "Python中用来表示空值的关键字是?",
            "choices": ["None", "null", "nil", "NaN"],
            "correct_answer": 1
        },
        {
            "question": "Python中用来表示真值的关键字是?",
            "choices": ["True", "Yes", "1", "T"],
            "correct_answer": 1
        }
    ]

    score = 0
    for question in questions:
        show_question(question["question"], question["choices"])
        user_choice = get_user_choice(question["choices"])
        if user_choice == question["correct_answer"]:
            score += 1

    print(f"您的分数是:{score}/{len(questions)}")

play_game()

以上代码中,play_game()函数实现了一个选择题游戏的逻辑。首先定义了一个问题列表,每个问题都包括问题描述、选项列表和正确答案。然后通过循环逐个显示问题,并接收用户输入的选择。如果用户输入的选择是一个有效的数字,在选项范围内,就将该选择与正确答案进行比较,如果相等则得分加一。最后打印出得分情况。

使用这个代码,用户可以通过命令行交互方式回答问题,选择正确答案,然后获得最后的得分。