[英]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.