Write a Python program to count the number of Monday of the 1st day of the month from 2014 to 2022


The program starts by importing the datetime module from the Python Standard Library.

  • A variable m1 is created and set to 0. This variable will be used to count the number of Mondays that occur on the first day of a month.
  • A month variable is created, which is a range of numbers from 1 to 12, representing the 12 months of a year.
  • A for loop is used to iterate over the years from 2014 to 2022 (inclusive). For each year, a nested for loop is used to iterate over the month range, representing each month of the year.
  • For each iteration of the inner loop, a datetime object is created using the datetime function. This object represents the first day of the month and year being considered. The weekday method of the datetime object is then called, which returns the day of the week as an integer (where Monday is 0, Tuesday is 1, and so on).
  • If the weekday method returns 0, it means that the first day of the month is a Monday. In this case, the m1 variable is incremented by 1 to keep count of the number of Monday first days of the month.
  • Finally, after both loops have completed, the value of m1 is printed, which represents the total number of Monday first days of the month between 2014 and 2022.

Source Code

import datetime
from datetime import datetime
m1 = 0
month = range(1,13)
for year in range(2014, 2022):
    for m in month:
        if datetime(year, m, 1).weekday() == 0:
            m1 += 1
print(m1)

Output

14

Example Programs