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

2024-04-26 06:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算调和平均值,如果我的列表“x”包含负值,则引发一个异常。 但代码不起作用。我如何调整我的for+if statemenst来解决问题? 谢谢

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

Tags: 代码in列表forifdefexceptionlist
2条回答

您好,如果您想更正您的答案,请认为它会有所帮助:

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

相关问题 更多 >