lecture 4.2 异常

1  try 

Suppose we rewrite the FancyDivide function to use a helper function.

def FancyDivide(list_of_numbers, index):
   denom = list_of_numbers[index]
   return [SimpleDivide(item, denom)
               for item in list_of_numbers]
def SimpleDivide(item, denom):
   return item / denom

This code raises a ZeroDivisionError exception for the following call: FancyDivide([0, 2, 4], 0)

Your task is to change the definition of SimpleDivide so that the call does not raise an exception. When dividing by 0, FancyDivide should return a list with all 0 elements. Any other error cases should still raise exceptions. You should only handle the ZeroDivisionError.

#define the SimpleDivide function here
def SimpleDivide(item, denom):
    try:
        return item / denom
        # catch a division by zero and return 0
    except ZeroDivisionError, e:
        return 0

e:表示的是异常的msg


2 assert

def Normalize(numbers):
    max_number = max(numbers)
    assert(max_number != 0), "Cannot divide by 0"
    for i in range(len(numbers)):
        numbers[i]  /= float(max_number)
        assert(0.0 <= numbers[i] <= 1.0), "output not between 0 and 1"
    return numbers        

assert(max_number != 0), "Cannot divide by 0"   #如果max_number != 0不成立 则抛出"Cannot divide by 0"  否则continue


上一篇:jq insertBefore 的返回值


下一篇:Web服务器- apache与nginx分析