Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to find the no of days of a certain month by taking month name as user input using python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CASE – 2:
Input: jule
Output: None

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading