pythonfunctionindexingmaxtypeerror

Python : How to properly implement a raise an exception in a function


I am trying to make a function that receives a list/array and returns the index of the maximum value in that sequence. The function should raise an exception if non-numerical values are present in the list.

def maxvalue(values):
    """
    Function that receives a list/array and returns the index of the maximum
    value in that sequence

    """    
    indices = []
    max_value = max(values)
    for i in range(len(values)):
        if type(i) not in (float, int): # raise an exception if the value is not float or integer
            raise TypeError("Only numberical values are allowed")
        if values[i] == max_value:
            indices.append(i)
    return indices

maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220])

The function works when it receives a list containing floats and integers and doesn't work if there is a string in it.

How do I get the function to produce "TypeError("Only numberical values are allowed")" error quote when there is a str present in the list?

Currently, it produces "TypeError: '>' not supported between instances of 'str' and 'float'"


Solution

  • The 'Comparison' happens in max function which raises an exception.

    You should do all checks, before your logic.

    def maxvalue(values):
        """
        Function that receives a list/array and returns the index of the maximum
        value in that sequence
    
        """
    
        try:
            max_value = max(values)
        except TypeError:
            raise TypeError("Only numerical values are allowed")
    
        indices = []
        for idx, val in enumerate(values):
            if val == max_value:
                indices.append(idx)
    
        return indices
    

    As you can see I am catching TypeError and re-raise it with different message. Also use enumerate in for loops.