Write a Python program to display a simple, formatted calendar of a given year and month


The program is a Python code that generates a calendar for a given year and month. First, the user is prompted to enter the year and month for which the calendar is to be generated. Then, the monthcalendar() function of the calendar module is used to generate a matrix of the calendar for the given month and year.

The program then formats and prints the calendar matrix in a more readable and organized format. The format includes the days of the week, the days of the month, and vertical lines as borders for the calendar.

The program prints the calendar for the given month and year in the following format:

|------MM-YYYY -------|
|Su Mo Tu We Th Fr Sa |
|---------------------|
| d  d  d  d  d  d  d |
| d  d  d  d  d  d  d |
| d  d  d  d  d  d  d |
| d  d  d  d  d  d  d |
| d  d  d  d  d  d  d |
|---------------------|

Where MM represents the two-digit month number, YYYY represents the four-digit year, and d represents a day of the month. The calendar includes vertical lines as borders and spaces between the days for readability.

Source Code

import calendar
 
y = int(input("Enter the Year :"))
m = int(input("Enter the Month of Number :"))
 
cal = calendar.monthcalendar(y, m)
 
if len(str(m)) == 1:
    m = '0%s' % m
 
print('\n|------%s-%s ------|' % (m, y))
print('|Su Mo Tu We Th Fr Sa|')
print('|--------------------|')
 
border = '|'
for week in cal:
    l = border
 
    for day in week:
        if day == 0:
      # 3 spaces for blank days       
         l += '   ' 
        elif len(str(day)) == 1:
            l += ' %d ' % day
        else:
         l += '%d ' % day
    # remove space in last column
    l = l[0:len(l) - 1]  
    l += border
    print(l)
 
print('|--------------------|')

Output

Enter the Year :2023
Enter the Month of Number :5

|------05-2023 ------|
|Su Mo Tu We Th Fr Sa|
|--------------------|
| 1  2  3  4  5  6  7|
| 8  9 10 11 12 13 14|
|15 16 17 18 19 20 21|
|22 23 24 25 26 27 28|
|29 30 31            |
|--------------------|

Example Programs