【问题标题】:Why am I getting this TypeError: unsupported format string passed to NoneType.__format__为什么我得到这个 TypeError: unsupported format string passing to NoneType.__format__
【发布时间】:2021-06-04 18:02:21
【问题描述】:

我必须在 csv 文件中找到一列数字的平均值。我知道有更简单的方法可以做到这一点,但我的代码不断返回这个错误,我不知道为什么。 TypeError:传递给 NoneType 的格式字符串不受支持。格式

def average_magnitude(file_name):
    magnitude = []
    row = []

    size = len(list(file))
    for each_line in file:
        each_line = each_line.strip()
        row = each_line.split(",")
        for each_num in file:
            s += each_num
        
        magnitude = s/size
        

def main(file_name):
    magnitude = average_magnitude(file_name)
    print("The average earthquake magnitude is {:.2f}\n".format(magnitude))

【问题讨论】:

  • 你的函数average_magnitude没有return语句,所以它返回None
  • 我刚试了,也遇到了同样的错误
  • @acompleteillusion:刚刚试过什么?您的问题是main 中的magnitudeNone。您未能从average_magnitudereturnfloat。解决方法是返回 float 无论如何(或引发异常)。
  • 这能回答你的问题吗? What is the purpose of the return statement?

标签: python-3.x csv string-formatting


【解决方案1】:

我想你可能只是打错字了。我认为for each_num in file 应该说for each_num in row

记得在那个加法操作中也做int(each_num) :)

另外,请确保从函数中返回一个值,否则它会自动返回 None。

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2018-06-12
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2020-10-03
    • 2022-01-23
    相关资源
    最近更新 更多