dimanche 23 février 2020

Python function with specific parameters as inputs, exceptions

I have a function mean_univ with three parameters and I want that it raises Errors if

  1. x is no list, e.g. a dictionary
  2. x contains other values than int or float, e.g. strings
  3. if the string you input as method is not "mean" or "tmean"
  4. if alpha isn't between 0 and 1

When I define for example x=[1,2,4,10,12] my code doesn't raise the Exception (3.) and I don't know how to implement the 2. and 4. Thanks.

def mean_univ(x, method, alpha=-1):
  if type(x) != list:
    return print("No list")
  if method == mean:
    return mean(x)
  elif method ==tmean:
    return tmean(x,alpha)
  else:
    raise Exception("wrong inputs. Try again")



def mean(x):
    return print(float(sum(x)) / max(len(x), 1))

def tmean(x, alpha):
  s = sorted(x)
  a = round(alpha * len(x))
  trimmed_list = s[a:-a]
  if len(trimmed_list) == 0:
    return
  trimmed_ave = sum(trimmed_list)/len(trimmed_list)
  return trimmed_ave


Aucun commentaire:

Enregistrer un commentaire