微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误和异常:C2M5L4_Errors_and_Exceptions-V2

如何解决错误和异常: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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。