Generator Public

Code #3399

Monthly Day and Saturday Count

This Python script calculates and displays the number of days and Saturdays for each month of a specified year. It utilizes the 'calendar' module to efficiently determine month ranges and weekly day occurrences.

Python
# main.py
import calendar

def display_month_info(year):
    """
    Displays information for each month of a given year, including the total number of days
    and the count of Saturdays in that month.

    Args:
        year (int): The year for which to display month information.
    """
    print(f'\nMonth Information for Year: {year}')
    print('-------------------------------------')

    # Loop through each month from January (1) to December (12)
    for month_num in range(1, 13):
        # Get the name of the month using calendar.month_name
        month_name = calendar.month_name[month_num]

        # calendar.monthrange returns a tuple: (weekday of first day, number of days)
        # We are interested in the number of days in the month (index 1)
        num_days_in_month = calendar.monthrange(year, month_num)[1]

        saturday_count = 0
        # calendar.monthcalendar returns a list of weeks, where each week is a list of 7 day numbers.
        # 0 represents a day not in the month. Days of the week are Monday(0) to Sunday(6).
        # Saturday is at index 5 of the week list.
        month_calendar_matrix = calendar.monthcalendar(year, month_num)

        # Iterate through each week in the month's calendar
        for week in month_calendar_matrix:
            # Check if the 6th element (Saturday) of the week is a valid day (not 0)
            if week[5] != 0:
                saturday_count += 1

        # Print the collected information for the current month
        print(f'{month_name:<10}: Days = {num_days_in_month:2d}, Saturdays = {saturday_count:1d}')

# --- Example Usage ---
if __name__ == '__main__':
    # Example 1: Display information for the current year
    import datetime
    current_year = datetime.datetime.now().year
    display_month_info(current_year)

    # Example 2: Display information for a specific year (e.g., 2024)
    display_month_info(2024)

    # Example 3: Display information for a past year (e.g., 2023)
    display_month_info(2023)
Prompt: displaying the months of the year with number of days and saturdays