关闭

function invocation with except handling DEMO

239人阅读 评论(0) 收藏 举报
分类:
#quote from MIT 'introduction to computation and programming using python, Revised' 
def getRatios(vect1, vect2):
    """Assumes: vect1 and vect2 are lists of equal length of numbers
       Returns : a list containing the meaningful values of
                 vect1[i]/vect2[i]"""
    ratios = []
    for index in range(len(vect1)):
        try:
            ratios.append(vect1[index]/float(vect2[index]))
        except ZeroDivisionError:
            ratios.append(float('nan')) #nan = Not a Number
        except:
            raise ValueError('getRatios called with bad arguments')
    return ratios

try:
    print getRatios([1.0, 2.0, 7.0, 6.0], [1.0, 2.0, 0.0, 3.0])
    print getRatios([], [])
    print getRatios([1.0, 2.0], [3.0])
except ValueError, msg:
    print msg


%run "C:\Users\Administrator\test.py"
[1.0, 1.0, nan, 2.0]
[]
getRatios called with bad arguments

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:90619次
    • 积分:2923
    • 等级:
    • 排名:第12516名
    • 原创:165篇
    • 转载:108篇
    • 译文:30篇
    • 评论:1条
    文章分类
    最新评论