Back to Practice Dashboard
Python BasicsEasy

Counting number of days in a given month of a year

Learn how to solve the 'Counting number of days in a given month of a year' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function days_in_month(month, year) that takes an integer month (1-12) and an integer year, and returns the number of days in that month.

Remember:

- Months with 31 days: January(1), March(3), May(5), July(7), August(8), October(10), December(12)

- Months with 30 days: April(4), June(6), September(9), November(11)

- February(2): 28 days normally, 29 days in a leap year

- Leap year: divisible by 4, but not by 100, unless also divisible by 400

Constraints
  • 1 <= month <= 12
  • 1 <= year <= 9999

Examples

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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor