【问题标题】:Whats wrong with this code for checking age?这段检查年龄的代码有什么问题?
【发布时间】:2022-11-23 10:13:39
【问题描述】:

我想知道输入的出生日期是否超过 18 岁或以下。

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
    )
)

接着:

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')

然而,唯一的事情是,假设我添加了一个用户,他的生日是 2004 年 11 月 25 日。程序让我添加它,因为它不计算月份。如果我添加一个出生于 2005 年 1 月 1 日的用户,它不允许我添加,因为 2022-2005=17。

【问题讨论】:

  • 无法重现。当我给它输入 2004、11、25 时,您的确切代码会打印 Under 18,这与日历的实际工作方式一致。
  • 这回答了你的问题了吗? Age from birthdate in python
  • 如果我添加一个 2005 年 1 月 1 日出生的用户,它不允许我因为 2022-2005=17我不明白。 2005 年 1 月 1 日出生的人要到 2023 年 1 月 1 日才会满 18 岁。所以这个代码应该说他们未满 18 岁,因为他们是.实际问题是什么?

标签: python python-3.x date


【解决方案1】:

您的原始代码似乎对您提到的日期没有问题,但确实有一个错误,因为 2004 年 11 月 22 日是“未满 18 岁”,而今天的日期是 2022 年 11 月 22 日(18 岁生日)。请改用now.day &lt; birth.day

但是如果你通过将今天的年份减去 18 来计算需要 18 岁的生日,然后直接比较日期,你不必进行复杂的比较:

from datetime import date

def is_under_18(birth):
    # today = date.today()
    today = date(2022,11,22) # for repeatability of results
    born_on_or_before = today.replace(year=today.year - 18)
    return birth > born_on_or_before

print(f'Today is {date.today()}')
for year,month,day in [(2004,11,21), (2004,11,22), (2004,11,23), (2004,11,25), (2005,1,1)]:
    birth = date(year,month,day)

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

输出:

Today is 2022-11-22
2004-11-21 Adult
2004-11-22 Adult
2004-11-23 Under 18
2004-11-25 Under 18
2005-01-01 Under 18

【讨论】:

    猜你喜欢
    • 2015-04-25
    • 2018-09-09
    相关资源
    最近更新 更多