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

Python反转布尔值函数输入0和1未返回自定义提示如何解决

错误原因

Python 中 bool 是 int 的子类,内置规则下 1 == True、0 == False 的判断结果都为 True。你的代码优先做值相等校验,所以整数1、0会直接命中布尔处理分支,不会走到后续的类型判断逻辑。

修复后的代码

要实现严格的布尔类型校验,优先判断输入的类型是否为bool即可:

def reverse_bool_value(value):
    # 优先判断是否为严格的布尔类型
    if type(value) is bool:
        return not value
    elif type(value) == int:
        return "Not Boolean Value"
    else:
        return "Boolean Expected"
测试结果验证
>>> reverse_bool_value(True)
False
>>> reverse_bool_value(False)
True
>>> reverse_bool_value(1)
'Not Boolean Value'
>>> reverse_bool_value(0)
'Not Boolean Value'
>>> reverse_bool_value(12)
'Not Boolean Value'
>>> reverse_bool_value("test")
'Boolean Expected'

完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:06:04