Python program to print the number of days in a month using dictionary

Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python program to print the number of days in a month using dictionary.

Code for python program to print the number of days in a month using dictionary

def days_in_month(month):
    days = {
        "january": 31,
        "february": 28,
        "march": 31,
        "april": 30,
        "may": 31,
        "june": 30,
        "july": 31,
        "august": 31,
        "september": 30,
        "october": 31,
        "november": 30,
        "december": 31
    }
    return days.get(month.lower(), 'Invalid month')

print(days_in_month('January'))
print(days_in_month('february'))
print(days_in_month('JunE'))
print(days_in_month('abc'))

Output

31
28
30
Invalid month

Explanation

In this program, the days_in_month() function takes one argument: a month. The function uses a dictionary where the keys are the months and values are the days of the month. The get method used on the dictionary with the month string converted to lower case as key. If the month passed is not found in the dictionary then it returns ‘Invalid month’

This is one way to use a dictionary to emulate a switch statement, but it’s not the only way. Another way would be to use if-elif-else block or a function with a default value.

Also keep in mind, this example is only considering the days in non-leap years, You should take Leap year into consideration in case if you want it to be accurate.

Conclusion

If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment