错误和异常:C2M5L4_Errors_and_Exceptions-V2

问题描述

import random

participants = ['Jack','Jill','Larry','Tom']

def Guess(participants):
    my_participant_dict = {}
    for participant in participants:
        my_participant_dict[participant] = random.randint(1,9)
    if my_participant_dict['Larry'] == 9:
        return True
    else:
        return False
    
print(Guess(participants))

解决方法

# Revised Guess() function
def Guess(participants):
    my_participant_dict = {}
    for participant in participants:
        my_participant_dict[participant] = random.randint(1,9)
    try:
        if my_participant_dict['Larry'] == 9:
            return True
    except KeyError:
        return None
    else:
        return False