# File: calendar.py # Some global values # January 1, 1900 was a Monday firstYear = 1900 firstYearWeekDay = 1 monthNames = [ "Not a Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Decenber" ] # Ask the user for a year for which to print # a calendar. # def getYear(): done = False while not done: aString = input("Enter year: ") year = int(aString) if year >= firstYear: done = True else: print("Enter a year after ", firstYear - 1) # end of while() return year # end of getYear() # Returns True or False depending on # whether the parameter year is a leap year. # def isLeapYear(year): if year % 4 != 0: return False if year % 100 != 0: return True if year % 400 == 0: return True else: return False # end of isLeapYear() # If the current day is a day of the week # given by the parameter weekday (e.g. Monday), # what day will it be in the number of days # given by the parameter days? # # For example, nextWeekDay(12, 1) return 6 # because 12 days from Monday is a Saturday. # def nextWeekDay(days, weekday): return (weekday + days) % 7 # Returns the day of the week for Jan 1 # in the year specified by the parameter year. # def weekDayJan1(year): # Doesn't work for years before firstYear if year < firstYear: print("Error: can't print calendars before", firstYear) exit() # start at firstYear weekday = firstYearWeekDay # figure out the week day of Jan 1 for # each year between firstYear and year. for y in range(firstYear, year): # figure out the start of the next year # if isLeapYear(y): weekday = nextWeekDay(366, weekday) else: weekday = nextWeekDay(365, weekday) return weekday # end of weekDayJan1() # Returns the number of days in month m of year y # def numberDays(m, y): # month numbered: Jan=1, Feb=2, ..., Dec=12 if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12: return 31 if m == 4 or m == 6 or m == 9 or m == 11: return 30 # must be February if isLeapYear(y): return 29 else: return 28 # end of numberDays() # # Prints the header for each month in the calendar # def printLabel(m, y): print(" ", monthNames[m], y) # end of printLabel() # # Prints the "body" of the monthly calendar for # a month with number of days specified by days # that starts on the day of the week specified # by weekday. # def printMonth(days, weekday): print(" Su Mo Tu We Th Fr Sa") # print blank spaces up to first day for d in range(weekday): print(" ", end="") for d in range(1, days+1): if (d + weekday) % 7 == 0: print("%3d" % d) else: print("%3d" % d, end="") print() if (d + weekday) % 7 != 0: print() # print("last d is", d) ; # end printMonth() def main(): # prompt user for a year year = getYear() # January 1 is Monday? Tuesday? weekday = weekDayJan1(year) for month in range(1,13): # make nice label for each month printLabel(month, year) # find out how long this month is days = numberDays(month, year) printMonth(days, weekday) weekday = nextWeekDay(days, weekday) # end of main() main()