How to tell if a year is a Leap Year in Python

1 min read 261 words

Given that we are in a leap year this year (2020), it would be nice to know how to programmatically calculate this.

Luckily, this is a repeatable pattern that we can write some code for.

So what is a leap year?

A leap year is a year that has 29 days in the month of February.

Astronomical years have a quarter of a day more than our calendar years that we follow, so to make sure this matches up continually, our calendar introduces an additional day every 4 years.

Building a pattern

The pattern we can follow to make sure that we write our code correctly is:

If the year is not divisible by 4 then it is a common year
Else if the year is not divisible by 100 then it is a leap year
Else if the year is not divisible by 400 then it is a common year
Else it is a leap year

Writing some code

We can easily turn this into code:

def isLeapYear(year):
  if year % 4 != 0:
    return False, "Common year"
  elif year % 100 != 0:
    return True, "Leap year"
  elif year % 400 != 0:
    return False, "Common year"
  else:
    return True, "Leap year"

Our function above takes in a year variable and returns two variables. A boolean is it is a leap year or not and a string telling us what it is.

Testing our code

Let’s test it!

print( isLeapYear(2020) )

# (True, 'Leap year')

print( isLeapYear(1999) )

# (False, 'Common year')

print( isLeapYear(1685) )

# (False, 'Common year')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags