You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何断言div_3函数返回值为list类型时触发AssertionError?

为什么assert type(div_3(data_list)) == list会触发AssertionError?

问题出在你的div_3函数没有返回值——Python里,函数如果没写return语句,默认会返回None。

你看到函数执行时能正确打印[12,15,36,21],那只是函数内部用print()输出了结果,但函数本身给调用者返回的是None。所以type(div_3(data_list))得到的是NoneType,不是list,断言自然失败。

修正方法

把函数里的print(output)改成return output,或者保留打印的同时加上return语句,让函数返回筛选后的列表:

错误的原函数

def div_3(data_list):
    output = []
    for num in data_list:
        if num % 3 == 0:
            output.append(num)
    print(output)  # 仅打印,无返回

修正后的函数

def div_3(data_list):
    output = []
    for num in data_list:
        if num % 3 == 0:
            output.append(num)
    print(output)  # 可选保留打印
    return output  # 关键:返回结果列表

这样调用div_3(data_list)时,既会打印结果,函数也会返回列表对象,断言type(div_3(data_list)) == list就能通过了。

内容的提问来源于stack exchange,提问作者JVR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:30:46