Advertisement
acclivity

pyPrintMonthCalendar

Nov 26th, 2022 (edited)
872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. # Print a calendar for a chosen year and month, highlighting a chosen day
  2.  
  3. month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  4. month_names = ["", "January", "February", "March", "April", "May", "June",
  5.                "July", "August", "September", "October", "November", "December"]
  6.  
  7. def get_int(prompt, low, high):
  8.     # A user function to get a valid integer within a specified range
  9.     while True:
  10.         try:
  11.             num = int(input(prompt))
  12.             if low <= num <= high:
  13.                 return num
  14.             raise Exception()
  15.         except:
  16.             print("Invalid input. Try again\n")
  17.  
  18. year = get_int("Enter the year: (1901 to 2099): ", 1901, 2099)
  19. month_days[2] = [29, 28, 28, 28][year % 4]              # Feb has 29 days in a leap year, otherwise 28
  20.  
  21. month = get_int("Choose a month: ", 1, 12)
  22. day = get_int("Choose a day from the given month: ", 1, month_days[month])
  23.  
  24. work = 2 + (year - 1901) * 365 + (year - 1901) // 4     # 365 days per year +1 per leap, start=Tues 1-1-1901
  25. month1st = 1 + (work + sum(month_days[:month])) % 7     # Day-of-week of 1st of month, base 1
  26.  
  27. heading = month_names[month] + " " + str(year)
  28. print(f"\n{heading:^29}")                   # print month and year, centred on line
  29. print(" Sun Mon Tue Wed Thu Fri Sat")       # print day abbreviations
  30. dayno = 2 - month1st                        # go back to the last Sunday before or equal to the 1st of this month
  31. while dayno <= month_days[month]:
  32.     for _ in range(7):                      # 7 days per print line
  33.         if dayno < 1 or dayno > month_days[month]:  # print spaces before month start and after month end
  34.             print("    ", end="")
  35.         else:
  36.             work = ['', '*'][dayno == day] + str(dayno)     # prefix chosen day with "*"
  37.             print(f"{work:>4}", end='')                     # print day number, right aligned
  38.         dayno += 1
  39.     print()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement