我需要通过使用 python [closed] 将月份名称作为用户输入来查找某个月的天数

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

提问人:Venkata pardhu Vemula 提问时间:11/15/2023 更新时间:11/15/2023 访问量:56

问:


想改进这个问题吗?通过编辑这篇文章来更新问题,使其仅关注一个问题。

9天前关闭。

通过将月份名称作为用户输入,我们必须找到该月所包含的天数。 如果月份名称不正确(例如用户拼写错误),我们必须打印“None”。

预期输出:

案例 - 1: 输入时间:1月 输出: 31

案例 - 2: 输入:jule 输出:无

python 用户输入

评论

0赞 Yevhen Kuzmovych 11/15/2023
欢迎来到 Stack Overflow!你似乎在要求某人为你编写一些代码。Stack Overflow 是一个问答网站,而不是代码编写服务。请参阅如何提问以了解如何编写有效的问题。
0赞 Tim Vielhauer 11/15/2023
您可以直接使用 calendar.monthrange: stackoverflow.com/questions/4938429/...
0赞 Codist 11/15/2023
@TimVielhauer 只有当你知道年份时

答:

0赞 Sash Sinha 11/15/2023 #1

为了处理闰年(即,在某些年份,二月可能有 29 天),您可以使用日历模块:

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

用法示例 1:

Enter the name of the month: January
31

用法示例 2:

Enter the name of the month: jule
None

用法示例 3:

Enter the name of the month: February
28