Python 基础知识简单

计算一年中给定月份的天数

“计算一年中给定月份的天数”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 days_in_month(month, year),它接受一个整数 month (1-12) 和一个整数 year,并返回该月的天数。

记住:

- 有 31 天的月份:一月 (1)、三月 (3)、五月 (5)、七月 (7)、八月 (8)、十月 (10)、十二月 (12)

- 有 30 天的月份:四月 (4)、六月 (6)、九月 (9)、十一月 (11)

- 二月(2):正常28天,闰年29天

- 闰年:能被 4 整除,但不能被 100 整除,除非也能被 400 整除

约束条件
  • 1 <= month <= 12
  • 1 <= year <= 9999

示例

Example 1
Input
days_in_month(2, 2024)
Output
29
Explanation

2024 is divisible by 4 and not by 100, so it's a leap year. February has 29 days.

Example 2
Input
days_in_month(1, 2023)
Output
31
Explanation

January always has 31 days regardless of the year.

Example 3
Input
days_in_month(2, 1900)
Output
28
Explanation

1900 is divisible by 100 but not by 400, so it's NOT a leap year. February has 28 days.

Need a Hint?
考虑使用特定于数字的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。