mercredi 26 février 2020

How to raise an exception when a list contains negative values

I want calculate the harmonic mean and raise an exception if my list "x" contains negative values. But the code is not working. How can I adjust my for + if statement to fix the problem? Thanks.

x=[1,2,3.0,-3,,-2,1]

def hmean(x):
  sum= 0.0
  for i in x:
    if i < 0:
      raise Exception("list contains negative values")
    else:
      sum = 0.0
      for i in x:
        sum+= 1.0 / i
      return print(float(len(x) / sum))

Aucun commentaire:

Enregistrer un commentaire