October 13, 2024

Python Program to Display Calendar of a Given Year

To display the calendar of a given year in Python, you can use the built-in calendar module. This module provides functions to work with dates and calendars. Here’s a simple program to display the calendar for a specific year:

1. Import the Calendar Module

The calendar module includes the TextCalendar and HTMLCalendar classes that you can use to generate calendar outputs.

2. Program to Display the Calendar

import calendar

def display_calendar(year):
    # Create a TextCalendar instance
    cal = calendar.TextCalendar(calendar.SUNDAY)
    
    # Generate the calendar for the specified year
    calendar_text = cal.formatyear(year)
    
    # Print the calendar
    print(calendar_text)

# Input the year
year = int(input("Enter the year: "))
display_calendar(year)

3. Example Output

When you run the program and input a year, it will display the calendar for that year. For example, if you enter 2024, the output will show the calendar for the year 2024.

4. Customizing the Calendar Output

If you want to customize the calendar format or display specific months, you can use other functions from the calendar module:

  • calendar.month(year, month): Displays the calendar for a specific month.
  • calendar.prmonth(year, month): Prints the calendar for a specific month.
  • calendar.Calendar(firstweekday=0): Create a custom calendar instance with a different first day of the week.

Example: Display Calendar for a Specific Month

def display_month(year, month):
    # Create a TextCalendar instance
    cal = calendar.TextCalendar(calendar.SUNDAY)
    
    # Generate the calendar for the specified month
    calendar_text = cal.formatmonth(year, month)
    
    # Print the calendar
    print(calendar_text)

# Input the year and month
year = int(input("Enter the year: "))
month = int(input("Enter the month (1-12): "))
display_month(year, month)

5. Summary

Using the calendar module in Python, you can easily display and customize the calendar for any given year or month. This module provides a straightforward way to work with dates and calendar information.