本文共 1238 字,大约阅读时间需要 4 分钟。
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 heredef 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
转载地址:http://ojdvl.baihongyu.com/