Python Function To Display A Calendar

In this tutorial, we will be looking at a python function to display a calendar, i.e. all the dates of a month, of any year. The year and month are inputted by the user. This is a very simple program and uses only one function.

Display Calendar

We import calendar module and then use that to print the output calendar using inputted month and year.

# Import the calendar module  
import calendar  

# Ask the user for month and year  
year = int(input("Enter year (yyyy format): "))  
month = int(input("Enter month (mm format): "))  

# Display the calendar  
print(calendar.month(year, month))

We first import the calendar module which is gonna be used. For this we use the command: import calendar. You can read more about calendar module here.

We then ask the user to input the year and month of the calendar that they want using int(input(“Enter year (yyyy format): “)) and int(input(“Enter month (mm format: “)). Here, input() prints the message on the console and also reads the input given as a string. But we want the input to be an int so that we can perform mathematical operations on them and for that we use int().

The input is taken in the form of yyyy for the year. For example: 1999, 2001, 1655, etc. Similarly we take month in the form of mm. For example: 05 for May, 12 for December, etc.

The module calendar has a function called month, which prints all the dates of a month for any year with days. Basically this calendar.month() function is used to print the month details. To use this function we pass the two inputs as parameters to calendar.month(). Therefore are function call becomes calendar.month(year, month).
NOTE: It also prints the month and year before printing the calendar.


Enter year (yyyy format): 1998
Enter month (mm format): 04
      April 1998
Mo Tu We Th Fr Sa Su
       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

So here it is a simple python function to display a calendar of inputted month and year.

Also read,

Find the difference of days between two dates in Python

Find all Sundays of a calendar year in Python

Leave a Reply

Your email address will not be published. Required fields are marked *