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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。