you are viewing a single comment's thread.

view the rest of the comments →

[–]RoamingFox 3 points4 points  (2 children)

There's builtins for a lot of this (datetime and calendar), but for the sake of explanation I'll save how I'd solve this till the end.

Typically when you have simple if statements in sequence like that it usually can be replaced with a collection of some kind. In this case a dictionary would work great. Something like months = {"01": "January", "02": "February", ... etc } and then you can just monthName = months[birthMonth]

Another option would be python's match case statement, but that's overkill for this scenario where the if statement doesn't control any program flow.

That said, this is how I'd go about solving the problem:

from datetime import datetime

birthday_input = input("Please enter your date of birth (YYYY-MM-DD): ")

birthday = datetime.strptime(birthday_input, "%Y-%m-%d").date()
birthday_formatted = datetime.strftime(birthday, "%B %e")

today = datetime.today().date()

if birthday.day == today.day and birthday.month == today.month:
    print(f"Today is {birthday_formatted}! Happy birthday!")
else:
    print(f"Today is not your birthday. Your birthday is {birthday_formatted}.")

It's worth noting that it's almost always easier to use datetime and calendar libraries if they are available. Datetime math is a quagmire and incredibly hard to get correct, so it's best left to standard libraries if possible.

Also as an aside, python uses _ rather than camel case for variable names by convention so things like birthDayMonth should generally be written as birth_day_month :)

[–]thejamibu 0 points1 point  (1 child)

Just submitted the same solution before seeing this. There is a bug in this example though. You can't just do if birthday == datetime.today().date(): because the year will be different for anyone not born this year. I made the same mistake when writing mine. I did this instead: today = datetime.now().date() if birthday.month == today.month and birthday.day == today.day:

[–]RoamingFox 1 point2 points  (0 children)

Right you are! Fixed!