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

如何将Python测验游戏代码重构为函数?

Python测验游戏的函数重构建议

下面拆解几个可独立成函数的模块,全程通过参数传递和返回值流转数据,避免依赖全局变量:

1. 抽离题库定义

把题库从主逻辑中分离,单独封装成函数,后续要扩展、修改或从外部文件加载题库时会更方便:

def get_question_pool():
    return {
        "How many legs does a spider have?": 'Eight',
        'What is the color of an Emerald?': 'Green',
        'What color are the stars on the American flag?': 'White',
        'How many planets in our solar system?': 'Eight',
        'What fruit keeps the doctor away?': 'Apple',
        'Where does Santa Claus Live?': 'The North Pole',
        'Which state is famous for Hollywood?': 'California'
    }

2. 提取答案验证逻辑

原代码中的正则匹配是核心验证规则,单独抽成函数后,既方便复用,也能快速调整验证规则(比如新增允许同义词、调整标点宽容度):

import re

def is_answer_correct(user_input, correct_answer):
    # 构建匹配规则:允许前缀冠词、前后空格、结尾标点,忽略大小写
    pattern = r'^(The|the|an|An)*\s*' + re.escape(correct_answer) + r'\s*[\.\?\!]*\s*$'
    return re.search(pattern, user_input, re.IGNORECASE) is not None

3. 封装单题交互流程

把「提问→获取答案→验证→反馈」的完整流程封装成函数,返回是否答对的结果,让主函数只负责总分统计和流程控制:

def ask_single_question(question, correct_answer):
    user_answer = input(f"{question} ")
    if is_answer_correct(user_answer, correct_answer):
        print('Nice Job!')
        return True
    else:
        print('Sorry, incorrect!')
        return False

4. 简化主流程

重构后的主函数逻辑清晰,只负责初始化数据、循环处理所有问题、统计最终得分:

import random

def main():
    score = 0
    q_pool = get_question_pool()
    
    # 遍历题库,每次随机抽取一个问题并移除
    while q_pool:
        question = random.choice(list(q_pool.keys()))
        correct_answer = q_pool.pop(question)
        if ask_single_question(question, correct_answer):
            score += 1
    
    print(f'Your total points are: {score}')

if __name__ == "__main__":
    main()

变量与返回值的使用说明

  • 拒绝全局变量:所有需要传递的数据(题库、问题、答案)都通过函数参数传入,结果通过返回值带出,每个函数都是独立的功能单元,调试和复用更高效。
  • 局部变量仅在函数内生效:比如score只在主函数中维护,pattern仅在验证函数内存在,避免变量污染。
  • 函数职责单一:每个函数只完成一件事(验证函数只判断对错,提问函数只处理单题交互),符合代码设计的单一职责原则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:12:56