How to print a given year calendar in python without calendar module

Share Your Love

How to print a given year calendar in Python without calendar module can be a bit more complex, as you’ll need to calculate the days and months yourself. However, it’s certainly possible. Here’s a simplified example of how you can print a one-year calendar using basic Python:

def is_leap_year(year):
    """Check if a year is a leap year."""
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def days_in_month(year, month):
    """Get the number of days in a month."""
    if month in {1, 3, 5, 7, 8, 10, 12}:
        return 31
    elif month in {4, 6, 9, 11}:
        return 30
    elif month == 2:
        return 29 if is_leap_year(year) else 28

def print_month(year, month):
    """Print the calendar for a specific month."""
    month_name = ["January", "February", "March", "April", "May", "June", "July",
                  "August", "September", "October", "November", "December"]
    print(f"{month_name[month - 1]} {year}")
    print("Su Mo Tu We Th Fr Sa")

    # Find the day of the week for the first day of the month
    first_day_weekday = (year + (year // 4) - (year // 100) + (year // 400) +
                         [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4][month - 1]) % 7

    for _ in range(first_day_weekday):
        print("   ", end=" ")

    for day in range(1, days_in_month(year, month) + 1):
        print(f"{day:2} ", end=" ")
        first_day_weekday += 1
        if first_day_weekday == 7:
            print()
            first_day_weekday = 0
    print("\n")

def print_year_calendar(year):
    """Print the calendar for the entire year."""
    for month in range(1, 13):
        print_month(year, month)

# Get user input for the year
year = int(input("Enter the year: "))
print_year_calendar(year)

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter