Knaph

The Year, Exactly2 of 32 min read

Leap Years in Python

The leap-year rule from the last lesson is three questions, asked in order:

The leap-year rule as three questions: divisible by 400 - leap year; otherwise divisible by 100 - not a leap year; otherwise divisible by 4 - leap year; otherwise not

A computer can follow it exactly. First, one tool.

Divisible? Ask for the remainder

In Python, % gives the remainder of a division. 2024 % 4 is 0, because 4 goes into 2024 exactly. 2023 % 4 is 3. So "is year divisible by 4?" is written:

year % 4 == 0
Python

The rule as a function

Each question in the picture becomes an if:

def is_leap(year):
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    return year % 4 == 0
 
 
print(is_leap(2024))  # True
print(is_leap(2023))  # False
print(is_leap(1900))  # False
print(is_leap(2000))  # True
Python

A return ends the function, so a later check only runs when the earlier ones didn't decide.

Why the order matters

Here is a version that looks reasonable but asks the questions the other way round:

def is_leap_wrong(year):
    if year % 4 == 0:
        return True
    if year % 100 == 0:
        return False
    if year % 400 == 0:
        return True
    return False
Python

Try 1900. It is divisible by 4, so the first if returns True straight away, and the century check never runs. Start with the rarest case (400), then the exception (100), then the common case (4).

In one line

The same rule fits in one expression: divisible by 4, and either not a century year or divisible by 400.

def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Python

Python's own calendar module has the same function built in, which is a good way to check yours:

import calendar
 
print(calendar.isleap(1900))  # False
Python

Big idea

A rule with exceptions becomes code by checking the most specific case first. % turns "divisible by" into a question a computer can answer.

Sign in to track your progress through this course.

Test your understanding

Sign in to test your understanding of this lesson.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.