How to Organize Python Code Into Functions

52 Views Asked by At

I created a (very) basic quiz game on Python that asks a question randomly chosen from a question pool. I've noticed on the Harvard CS50 tutorials that a lot of components can be turned into functions for further abstraction. I don't know how to do this because local and global variables along with return values trip me up. Does anyone have feedback for what can be made into a function?

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()
0

There are 0 best solutions below