关闭

exception as a control flow mechanism

190人阅读 评论(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 


%run "C:\Users\Administrator\test.py"


v1 = [10, 20, 100]


v2 = [2, 0, 3]


getRatios(v1, v2)
Out[95]: [5.0, nan, 33.333333333333336]


v2 = [2, 'hello', 5]


getRatios(v1, v2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-97-2772b9368d81> in <module>()
----> 1 getRatios(v1, v2)


C:\Users\Administrator\test.py in getRatios(vect1, vect2)
     11             ratios.append(float('nan')) #nan = Not a Number
     12         except:
---> 13             raise ValueError('getRatios called with bad arguments')
     14     return ratios
     15 


ValueError: getRatios called with bad arguments

0
0

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