我的代码是打印列表中元组的平均值,如果列表为空则返回None。现在这是我的代码
def average_vehicles(vehicle_records):
"""Return average of vehicles"""
summ = 0
num = 0
average = 0
if vehicle_records != []:
for value in vehicle_records:
summ += value[1]
num += 1
average = summ / num
else:
average = "None"
return average
我得到了此测试代码的正确输出:
some_records = [('2010-01-01',100),
('2010-01-02',200),
('2010-01-03',300)]
avg = average_vehicles(some_records)
print(avg)
但是我无法打印出来#34;好的"对于以下测试代码而且我不确定为什么当其他一切看起来不正常时,有人可以帮忙吗?
some_records = []
avg = average_vehicles(some_records)
if avg is None:
print('OK')
else:
print('The function should return a None value')
答案 0 :(得分:1)
您将返回字符串"None"
而不是对象None
答案 1 :(得分:0)
None
和"None"
不是一回事。
答案 2 :(得分:0)
None不应该是字符串而是None对象。
将以下行average = "None"
更改为average = None
,它应该有效。
答案 3 :(得分:0)
some_records = []
avg = average_vehicles(some_records)
if avg == "None":
print('OK')
else:
print('The function should return a None value')
答案 4 :(得分:0)
some_records = []
avg = average_vehicles(some_records)
if avg == 'None':
print('OK')
else:
print('The function should return a None value')
说明:
当我们打印avg
的类型时,它的类型为str
,但如果我们选中avg is None
,则此None
的类型为Nonetype
。所以我们需要检查使用"无"作为avg == 'None'