-1

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))
hblanc28
  • 29
  • 5
  • unindent the `return`, it should have the same indent level as the `for` statement. also you shouldn't combine `return` and `print` like that, just stick to `return` in this case – Dan Feb 26 '20 at 10:56
  • `sum` is a python function u cant use it as a variable name. – CC7052 Feb 26 '20 at 10:58
  • 1
    what is your output? – ginkul Feb 26 '20 at 10:58
  • @CC7052: You ***can*** use it as a variable name, but you won't be call to use the built-in function `sum()` afterwards if you do. – martineau Feb 26 '20 at 11:08
  • 1
    hblanc28: I suggest you get your code working on lists that don't have negative values first, then add a check for those afterwards. – martineau Feb 26 '20 at 11:09

2 Answers2

2

There are several problems with this code:

def hmean(x):
  for i in x:
    if i < 0:
      raise Exception("list contains negative values")
  # no need for else:, we come here if exception is not raised
  s = 0.0 # do not use sum as variable name
  for i in x:
    s += 1.0 / i
  return float(len(x)) / s # return needs to be outside the for loop; also, no print() here
Błotosmętek
  • 12,717
  • 19
  • 29
1

Hi if you want to correct your answer think it will help:

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

def hmean(x):
    s= 0.0
    for i in x:
        if i < 0:
            raise Exception("list contains negative values")
        else:

            s += 1.0 / i
    return float(len(x) / sum)
hm = hmean(x)
print(hm)
CC7052
  • 563
  • 5
  • 16