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

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:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```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"
```Code language: Python (python)```

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')```Code language: Python (python)```
Tags:
Subscribe
Notify of