In this example, you will write a Python program to check whether the date is a leap year or not in three different ways.
Example 1: Using the modulus operator
In this example, we check if the year is divisible by 4, but not by 100 except when it is also divisible by 400. Since 2024 is divisible by 4 and not by 100, it is a leap year, and “Leap year” is printed.
year = 2024
# Check if year is divisible by 4, but not by 100 except when it is also divisible by 400
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print("Leap year")
else:
print("Not a leap year")
Output
Leap year
Example 2: Using the Python calendar module
This method uses the isleap() function of the calendar module to check if 2022 is a leap year. Since 2022 is not a leap year, “Not a leap year” is printed.
import calendar
year = 2022
# Use the isleap() function of the calendar module to check if year is a leap year
if calendar.isleap(year):
print("Leap year")
else:
print("Not a leap year")
Example 3: Using datetime module
In this example, we use a strftime() method of the datetime module to check if 2000 is a leap year. Since 2000 is divisible by 4 and also by 400, it is a leap year, and “Leap year” is printed.
import datetime
year = 2000
# Use the strftime() method of the datetime module to check if year is a leap year
if datetime.date(year, 1, 1).strftime('%L') == '1':
print("Leap year")
else:
print("Not a leap year")
Output:
$ Leap year