A leap year is a year that has 366 days instead of the usual 365. It occurs every four years and is the year when an extra day, February 29th, is added to the calendar. This day, known as a leap day, helps to keep the calendar aligned with the Earth’s movements around the sun. Leap years occur every four years, with the next one occurring in 2024.

We can check whether a year is a leap year in Python in a few ways.

1. isleap() from calendar

The first method is by using a method isleap from the calendar:

 from calendar import isleap
 ​
 year=input('Write a year: ')
 ​
 if isleap(int(year)):
    print("This year is a leap year", year)
 else:
    print("This is not a leap year")

2. Number of days from monthrange()

There is another method inside the calendar module that returns the number of days in a month. We can simply check the number of the days in February. If the number of days in February is 29, then this is a leap year.

To do that, first, import the calendar module and then call the method monthrange() which returns the first_day and also the number_of_days in a month.

 import calendar
 ​
 # Get current month
 year = 2023
 ​
 while True:
     _, number_of_days = calendar.monthrange(year, 2)
 ​
     if number_of_days == 29:
         print("February has 29 days in {}".format(year))
         break
 ​
     year += 1

3. Check whether the year is divisible by 4 or 400

If a year is divisible by 4 and 100 and 400, then this number is actually a leap year. It is a leap also if it is divisible by 4 and not by 100:

 # Check if the year is a leap year
 ​
 def is_leap(year):
     leap = False
 ​
     # Write your logic here
     if year % 4 == 0:
         if year % 100 == 0:
             if year % 400 == 0:
                 leap = True
             else:
                 leap = False
         else:
             leap = True
     else:
         leap = False
 ​
     return leap
 ​
 ​
 a = is_leap(2024)
 print(a)  # True

That’s basically it.

I hope you find these tips useful.