Days in a month

EasyIf-Else Programs · 34 of 64

Write a Python program to convert a month name to its number of days.

Advertisement
Input
"February", "April", "July"
Output
February -> 28/29 days
april -> 30 days
July -> 31 days
Smarch -> invalid month

Approach

  1. Group months by their length with in.

Solution

Python
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.

More if-else programs

← All 64 If-Else Programs

Leave a Comment