【发布时间】: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