def longest(words): # attempt a for loop over the parameter, hoping it is iterable # if not, a TypeError occurs try: maxWord = '' empty = True # is the sequence empty? nonstring = False # does the sequence contain a nonstring? for w in words: # this might cause a TypeError empty = False # if we got this far, there is at least one item if not isinstance(w, str): nonstring = True # this is a problem else: if len(w) > len(maxWord): maxWord = w except TypeError: # problem with the for loop raise TypeError('sequence must be iterable') if empty: raise ValueError('sequence must be nonempty') if nonstring: raise TypeError('sequence elements must be strings') # if we get this far, we have a legitimate answer return maxWord