提问人:Venkata pardhu Vemula 提问时间:11/15/2023 更新时间:11/15/2023 访问量:56
我需要通过使用 python [closed] 将月份名称作为用户输入来查找某个月的天数
I need to find the no of days of a certain month by taking month name as user input using python [closed]
问:
通过将月份名称作为用户输入,我们必须找到该月所包含的天数。 如果月份名称不正确(例如用户拼写错误),我们必须打印“None”。
预期输出:
案例 - 1: 输入时间:1月 输出: 31
案例 - 2: 输入:jule 输出:无
答:
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
评论