Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Print a calendar for a chosen year and month, highlighting a chosen day
- month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- month_names = ["", "January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"]
- def get_int(prompt, low, high):
- # A user function to get a valid integer within a specified range
- while True:
- try:
- num = int(input(prompt))
- if low <= num <= high:
- return num
- raise Exception()
- except:
- print("Invalid input. Try again\n")
- year = get_int("Enter the year: (1901 to 2099): ", 1901, 2099)
- month_days[2] = [29, 28, 28, 28][year % 4] # Feb has 29 days in a leap year, otherwise 28
- month = get_int("Choose a month: ", 1, 12)
- day = get_int("Choose a day from the given month: ", 1, month_days[month])
- work = 2 + (year - 1901) * 365 + (year - 1901) // 4 # 365 days per year +1 per leap, start=Tues 1-1-1901
- month1st = 1 + (work + sum(month_days[:month])) % 7 # Day-of-week of 1st of month, base 1
- heading = month_names[month] + " " + str(year)
- print(f"\n{heading:^29}") # print month and year, centred on line
- print(" Sun Mon Tue Wed Thu Fri Sat") # print day abbreviations
- dayno = 2 - month1st # go back to the last Sunday before or equal to the 1st of this month
- while dayno <= month_days[month]:
- for _ in range(7): # 7 days per print line
- if dayno < 1 or dayno > month_days[month]: # print spaces before month start and after month end
- print(" ", end="")
- else:
- work = ['', '*'][dayno == day] + str(dayno) # prefix chosen day with "*"
- print(f"{work:>4}", end='') # print day number, right aligned
- dayno += 1
- print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement