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

年龄验证代码逻辑问题排查:判断是否未满18岁的代码错误分析

排查并修正“判断是否年满18岁”的Python代码逻辑错误

原代码的核心问题

原函数is_under_18的日期判断逻辑存在边界错误:

  • 当年份差刚好为18年时,代码用now.day <= birth.day判定,会把生日当天误判为未满18岁,但实际上生日当天已经年满18。
  • 这直接导致了用户提到的两个测试场景错误:
    1. 2004年11月25日生日当天,程序错误输出Under 18;
    2. 2005年1月1日在2023年1月1日(年满18当天),程序因<=的错误判定为Under 18。

修正后的代码

首先补充原代码缺失的date导入,然后修正日期判断的边界条件:

from datetime import date

def is_under_18(birth):
    now = date.today()
    return (
        now.year - birth.year < 18
        or now.year - birth.year == 18 and (
            now.month < birth.month 
            or now.month == birth.month and now.day < birth.day  # 将<=改为<,修正生日当天的判定
        )
    )

调用代码(需补充导入):

from datetime import date

year = int(input("Year born: "))
month = int(input("Month born: "))
day = int(input("Day born: "))
birth = date(year, month, day)

if is_under_18(birth):
    print('Under 18')
else:
    print('Adult')

修正逻辑说明

  • 年份差小于18:直接判定为未满18岁;
  • 年份差等于18:
    • 当前月份 < 生日月份 → 未满18;
    • 月份相同,但当前日期 < 生日日期 → 未满18;
    • 其余情况(月份大于生日月,或同月且日期≥生日)→ 已年满18岁。

测试验证

  • 2004年11月25日,当天为2022年11月25日:函数返回False,输出Adult,符合预期;
  • 2005年1月1日,当天为2023年1月1日:函数返回False,输出Adult;当天为2022年12月31日:函数返回True,输出Under 18,均符合实际年龄判定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:45:42