# isOkDate-7.12.py # Determine whether a calendar date in the form mm/dd/yyyy is OK # Neal Nelson 2007.11.07 # This program illustrates the import of a user module # This program can also be used as an module import # The program is uninformative about why a date is not OK. import string from isLeapYear import isLeapYear # Because these tables are constant we can define them globally daysInMonth = [31,28,31,30,31,30,31,30,31,31,30,31] daysInLeapMonth = [31,29,31,30,31,30,31,30,31,31,30,31] # Short circuit evaluation of "and" operation (p256 Zelle) insures # that month, day, and year are correct before calling isOkDay. # Zelle calls this the "operational" definition of the boolean operators. def isOkDate(m,d,y): return isOkYear(y) and isOkMonth(m) and isOkDay(m,d,y) def isOkYear(y): return y > 0 def isOkMonth(m): return m >= 1 and m <= 12 # month, day, year must already be OK. def isOkDay(m,d,y): if isLeapYear(y): return d >= 1 and d <= daysInLeapMonth[m-1] else: return d >= 1 and d <= daysInMonth[m-1] def main(): print "This program determines whether a date in form mm/dd/yyyy is OK" try: dateStr = raw_input("Enter date (mm/dd/yyyy): ") dayStr, monthStr, yearStr = string.split(dateStr, '/') if isOkDate(int(dayStr), int(monthStr), int(yearStr)): print "Yes, %s is a well formed date" % dateStr else: print "No, %s is not a well formed date" % dateStr except: print "An input date must be in form mm/dd/yyyy, all with integers" # Execute main only if this file is invoked directly from Python if __name__ == "__main__": main()