当列表包含负值时如何引发异常

How to raise an exception when a list contains negative values

我想计算调和平均值并在我的列表 "x" 包含负值时引发异常。 但是代码不起作用。如何调整我的 for + if statement 来解决问题? 谢谢

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))

嗨,如果您想更正您的答案,我认为这会有所帮助:

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)

这段代码有几个问题:

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