Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Today we are going to use Python to do a small function, that is to implement a perpetual calendar query.
def is_leap_year(year): if year/4==0 and year/400 ! =0: return True elif year/100 == 0 and year/400 ==0 : return True else: return FalseCopy the code
First check if it’s a leap year, because it’s useful to count whether there are 29 days in February.
Def getMonthDays (year, month) : 31 days = # 31 days, set to the default value if the month = = 2: # 2 month to determine whether a leap year if is_leap_year (year) : 29 days = the else: days=28; Elif month in [4,6,9,11]: # elif month in [4,6,9,11]: # elif month in [4,6,9,11]Copy the code
Gets the number of days in the month of the specified month from year and month.
Def def totalDays (year,month): totalDays=0 for I in range(1990,year): def totalDays (year,month): 0 for I in range(1990,year): TotalDays += 366 else: totalDays += 365 for I in range(1,month): TotalDays +=getMonthDays(year, I) return totalDaysCopy the code
Get the number of days since 1990-01-01, 1990-01-01 is Monday, using this as the criterion.
if __name__ == '__main__': while True: Print "x x x x x x x x x x python implementation calendar x x x x x x x x" year = raw_input (" please enter the date (such as: 1990) : ") the month = raw_input (" please enter the month, such as: 1) the try: Year = int(year) month = int(month) if month <1 or month >1: print "" Continue except: print "year or month" Continue break print "day \t 1 \t 2 \t 3 \t 5 \t 6" iCount = 0 for I in range(getTotalDays(year,month)%7): Print '\t', iCount+=1 for I in range(1,getMonthDays(year,month)): Print I, print '\t', iCount +=1 if iCount%7 == 0:Copy the code
Finally, just type in the year and month to type out the complete calendar for the entire month. Whether it is a query for a past calendar or a query for a future calendar, it can be calculated.
You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.