By taking month name as user input we have to find the no of days that month consits. If the month name is incorrect (like if the user did spelling mistake) we have to print "None".
Expected Output:
CASE - 1: Input: January Output: 31
CASE - 2: Input: jule Output: None
In order to handle leap years (i.e., in some years February might have 29 days), you can use the calendar
module:
import calendar
from datetime import datetime
from typing import Optional
MONTH_INDEX_BY_MONTH_NAME = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6,
'july': 7,
'august': 8,
'september': 9,
'october': 10,
'november': 11,
'december': 12,
}
def get_days_of_month(month: str) -> Optional[int]:
"""Gets the number of days in a given month for current year."""
month = month.lower()
year = datetime.now().year
if month in MONTH_INDEX_BY_MONTH_NAME:
return calendar.monthrange(year, MONTH_INDEX_BY_MONTH_NAME[month])[1]
return None
def main() -> None:
user_input = input("Enter the name of the month: ")
days = get_days_of_month(user_input)
print(days)
if __name__ == '__main__':
main()
Example Usage 1:
Enter the name of the month: January
31
Example Usage 2:
Enter the name of the month: jule
None
Example Usage 3:
Enter the name of the month: February
28