如何将Python代码组织成函数

问题描述 投票:0回答:1

我在 Python 上创建了一个(非常)基本的问答游戏,它提出一个从问题库中随机选择的问题。我在哈佛 CS50 教程中注意到,很多组件可以转化为函数以进行进一步抽象。我不知道如何做到这一点,因为局部变量和全局变量以及返回值让我困惑。有人对可以做成函数的东西有反馈吗?

import random
import re

def main():
    score = 0 
    q_pool = {"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'}

    for val in range(len(q_pool)): 
        random_key = random.choice(list(q_pool.keys()))
        answer = input(str(random_key))
        regex = r'^(The|the|an|An)*\s*' + re.escape(str(q_pool[random_key])) + r'\s*[\.\?\!]*\s*$'
        if re.search(regex, answer, re.IGNORECASE): 
            print('Nice Job!')
            score = score + 1
        else: 
            print('Sorry, incorrect!')
        del q_pool[random_key]
    print(f'Your total points are: {score}')
    return None

main()
python function return global-variables local-variables
1个回答
0
投票

我看到了这个视频,我认为它对于何时以及为何将 Python 代码分解为函数提供了非常好的建议;

https://www.youtube.com/watch?v=CFRhGnuXG-4

© www.soinside.com 2019 - 2024. All rights reserved.