简体   繁体   English

类型错误:+ 不支持的操作数类型:“NoneType”和“float”,同时循环和添加

[英]TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' while looping and adding

while running the below code I am getting TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' As per my requirement, I have a list of floating points numbers as string from an API, I want to convert them to float and find the avg在运行下面的代码时,我得到 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' 根据我的要求,我有一个浮点数列表作为来自 API 的字符串,我想转换它们浮动并找到平均值

a= None
l=['2.35','4.25','9.9']
for num in l:
  a=a+float(num)
avg=a/len(l)

You should initiate your variable a to 0 instead of None .您应该将变量a初始化为0而不是None This will give you:这会给你:

a = 0
l=['2.35','4.25','9.9']
for num in l:
  a=a+float(num)
avg=a/len(l)

The error you have tells you that you cannot sum a None object with a float, which is exactly what you are trying to do at your first iteration of for loop.您遇到的错误告诉您,您不能将None object 与浮点数相加,这正是您在 for 循环的第一次迭代中尝试做的事情。

When you initiate your variable a to 0 , you instead perform an addition of two numerical values, which is accepted by Python.当您将变量a初始化为0时,您改为执行两个数值的相加,这被 Python 接受。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError: 不支持的操作数类型 -: 'float' 和 'NoneType' - TypeError: unsupported operand type(s) for -: 'float' and 'NoneType' TypeError不支持%:Float和NoneType的操作数类型 - TypeError unsupported Operand type(s) for %: Float and NoneType TypeError:+不支持的操作数类型:“ NoneType”和“ float” - TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' TypeError:%不支持的操作数类型:“ NoneType”和“ float” - TypeError: unsupported operand type(s) for %: 'NoneType' and 'float' TypeError:/:不支持的操作数类型:“ NoneType”和“ float” - TypeError: unsupported operand type(s) for /: 'NoneType' and 'float' RaspberryPi Python 类型错误:不支持 * 的操作数类型:'NoneType' 和 'float' - RaspberryPi Python TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' 发生异常:TypeError 不支持 * 的操作数类型:'NoneType' 和 'float' - Exception has occurred: TypeError unsupported operand type(s) for *: 'NoneType' and 'float' Python TypeError:/:'NoneType'和'float'不支持的操作数类型 - Python TypeError: unsupported operand type(s) for /: 'NoneType' and 'float' 支付率程序(类型错误:* 不支持的操作数类型:'NoneType' 和 'float') - Pay Rate program (TypeError: unsupported operand type(s) for *: 'NoneType' and 'float') 使用打印语句获取类型错误:% 不支持的操作数类型:'NoneType' 和 'float' - Getting TypeError: unsupported operand type(s) for %: 'NoneType' and 'float' with a print statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM