Python Practice › If-Else Programs › Program 34
Days in a month
Write a Python program to convert a month name to its number of days.
Input
"February", "April", "July"
Output
February -> 28/29 days april -> 30 days July -> 31 days Smarch -> invalid month
Approach
- Group months by their length with
in.
Solution
def days_in(month): month = month.capitalize() if month == "February": return "28/29 days" elif month in ("April", "June", "September", "November"): return "30 days" elif month in ("January", "March", "May", "July", "August", "October", "December"): return "31 days" else: return "invalid month" for m in ["February", "april", "July", "Smarch"]: print(m, "->", days_in(m))Output
February -> 28/29 days april -> 30 days July -> 31 days Smarch -> invalid month
Line by line
Line 2
capitalize() accepts any letter case from the user.
Lines 5-8
Tuples list the 30-day and 31-day months.
Learn the concept
New to this topic? Read the lesson, then come back.