Assume that you have written the following code to find the middle element from a 3-element list.
def findmiddle(a): if ((a[0] >= a[1]) and (a[1] >= a[2])) or ((a[0] <= a[1]) and (a[1] <= a[2])): return a[1] elif ((a[0] >= a[2]) and (a[2] >= a[1])) or ((a[0] <=a[2]) and (a[2] <= a[1])): return a[2] else: return a[0]
Notice that if a list is passed in that is not of length at least 3, the code will give an error. Modify the function so that it will raise an exception if the list is not valid. Then, show how you could call the function, printing a message if there was an exception.
Can you tell how can i raise exception if there’s nothing come out if I run this code?
Advertisement
Answer
Within the function raise an exception and in the main program catch that exception… Like this
def findmiddle(a): assert len(a)>=3, "Invalid" if ((a[0] >= a[1]) and (a[1] >= a[2])) or ((a[0] <= a[1]) and (a[1] <= a[2])): return a[1] elif ((a[0] >= a[2]) and (a[2] >= a[1])) or ((a[0] <=a[2]) and (a[2] <= a[1])): return a[2] else: return a[0] L1, L2 = [1,2], [i for i in range(1, 11)] try: print(findmiddle(L2)) print(findmiddle(L1)) except AssertionError: print("List not big enough.")