简体   繁体   中英

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'"

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 numberical 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.

def maxvalue(values):
  indices = []
  print(values)
  int_values = []
  """the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value"""
  for x in values: 
      if type(x)==int:
          int_values.append(x)

  max_value = max(int_values)

  for i in range(len(int_values)):
      if int_values[i] == max_value:
              indices.append(i)
  return indices

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM