[Tutor] Re: Calendar question

jfouhy at paradise.net.nz jfouhy at paradise.net.nz
Wed Apr 6 03:15:53 CEST 2005

Quoting John Carmona <jeannot18 at hotmail.com>:

Hi John,

Some comments ---

> import calendar
> MonthName = {'January': 1,'February': 2, 'March': 3,'April': 4\
>  ,'May': 5,'June': 6,'July': 7,'August': 8,\
>  'September': 9,'October': 10,'November': 11,'December': 12}

You can actually get away with leaving out the backslashes.  ie, if I were
writing this code, I would probably write something like this:

MonthName = { 'January':1, 'February':2, 'March':3, 'April':4,
              'May':5, 'June':6, 'July':7, 'August':8,
              'September':9, 'October':10, 'November':11, 'December':12 }

(I'm not sure what the preferred convention for whitespace is ... I always leave
a space after the comma, but have no whitespace surrounding the colon, because
that makes it clearer that the two things either side of the ':' are a linked unit)

> ##By the way do the number have to be under that format??

I don't understand the question, sorry..

> calendar.setfirstweekday(0)
>  ##setfirstweekday change the day to what you want it be
>  ## 0=Monday, 6=Sunday.
> year = int(raw_input("Enter a year: "))
> month = (raw_input("Enter a month: "))            # ***
> MonthName_int = int(MonthName)                    # ***
> print calendar.prmonth(year,month)

Try replacing the lines I have marked with:

monthString = raw_input("Enter a month: ")
month = MonthName[monthString]

You might want to review the tutorial section on dictionaries:


If you want more robustness, you could try replacing those two lines with this:

monthString = raw_input('Enter a month: ')
while monthString not in MonthName:
    print "Unknown month!"
    monthString = raw_input('Enter a month: ')
month = MonthName[monthString]

This will check to see if the user's input is one of the keys in your
dictionary, and if not, it will ask again.



More information about the Tutor mailing list