I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month, using a list like this below:
I put in the correction at the bottom, thanks for the help
month_days= [('January',[31]),('February',[28,29]),('March',[31]), ('April',[30]),('May',[31]),('June',[30]),('July',[31]),('August',[31]),('September',[30]),('October',[31]),
('November',[30]),('December',[31]) ]
def month_day(mnth):
for m, d in month_days:
if m == mnth:
return d
This seems like it may be a homework assignment, but if it's not you can use the monthrange
function in the calendar
module (as described in this SO question):
>>> months = ['January','February','March','April','May','June', 'July','August','September','October','November','December']
>>> from calendar import monthrange
>>> for i in range(len(months)):
... ind = i+1
... print months[i], monthrange(2012,ind)[1] # returns a tuple, second element is number of days
...
January 31
February 29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
You may want to define the year dynamically since that determines whether it's a leap year or not, but otherwise this seems to give the data you want.
Don't invent a bike. Just use the calendar module http://docs.python.org/library/calendar.html
Here's a very basic way of traversing the list, finding the right month and returning the number of days. This is not a complete or optimal solution, just an example so you can build up on it.
month_days_list = [('January',[31]),('February',[28,29]),('March',[31]), ... ]
def month_days(month):
for m, d in month_days_list:
if m == month:
return d[0]
You should do something about the months that have more than one option of days, instead of just returning d[0].
return dict(month_days_list)[month][0]
- Gareth Latty 2012-04-04 20:11
FYI in general the simplest way to solve this type of problem (given a string print a constant) is with a dictionary:
month2days = { 'January': 31, 'February': 29, } ## and so on
print (month2days['January'])
will print 31
Using a list of tuples is not the best way.
month_days('February')
? Also, what's your code - Niklas B. 2012-04-04 19:51