-2

I want to know if inputed date of birth is over 18 or under.

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

And then:

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

However, the only thing is, say I add a user which his birthday is the 25th of November 2004. The program lets me add it because it does not count the month. If I add a user which was born the 1st of January 2005, it doesn't allow me because 2022-2005=17.

  • 2
    Cannot reproduce. Your exact code prints `Under 18` when I give it the inputs 2004, 11, 25, which is consistent with how a calendar actually works. – Silvio Mayolo Nov 23 '22 at 01:36
  • Does this answer your question? [Age from birthdate in python](https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python) – Michael Ruth Nov 23 '22 at 01:38
  • 1
    _If I add a user which was born the 1st of January 2005, it doesn't allow me because 2022-2005=17_ I don't understand. Someone who was born on 1 Jan 2005 won't turn 18 until 1 Jan 2023. So this code _should_ say they are under 18, because _they are_. What is the actual problem? – John Gordon Nov 23 '22 at 01:52

1 Answers1

0

Your original code doesn't seem to have a problem with the dates you mention, but does have a bug as Nov 22, 2004 is "Under 18" and today's date is Nov 22, 2022 (18th birthday). Use now.day < birth.day instead.

But if you compute the birthday required to be 18 by replacing today's year with 18 less, then directly compare the dates, you don't have to have a complicated comparison:

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

Output:

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251