Check Leap Year in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Gregorian

What You’ll Learn

A Gregorian leap year has February 29 under the 4 / 100 / 400 divisibility rules. This tutorial covers the predicate, century exceptions, a live preview, worked Python examples, edge cases, and complexity.

Definition

Feb 29

Leap years insert an extra day under Gregorian rules.

4 / 100 / 400

Predicate

(y%4==0 and y%100!=0) or (y%400==0).

Classic 2024

Leap

Divisible by 4 and not a century year.

Centuries

1900 vs 2000

1900 fails; 2000 passes (% 400).

Live Preview

Try any year

Instant Gregorian leap verdict in the browser.

O(1)

Per year

A few modulus checks; range scan is linear.

Introduction

A leap year in the Gregorian calendar has February 29. The arithmetic rule is: divisible by 4, except century years, which must also be divisible by 400.

Example: 2024 is leap (divisible by 4, not by 100). 1900 is not; 2000 is — because of the % 400 override.

Why it matters?

Leap rules show up in date validation, scheduling, and interview prompts that test careful boolean logic with modulus.

Key Highlights

One Predicate

A short boolean expression decides leap vs common.

Century Trap

% 100 alone would wrongly reject 2000.

Two Styles

One-liner boolean or nested ifs.

Proleptic Formula

Code applies the rule uniformly to integer years.

In short: leap if divisible by 4 but not by 100, unless also divisible by 400.

📝 Problem & Approach

Given an integer year y, decide whether it is a Gregorian leap year.

python
# 2024 → %4==0, %100!=0          → leap
# 1900 → %100==0, %400!=0         → not
# 2000 → %400==0                  → leap
# 2021 → %4!=0                    → not

Inputs & Outputs

ItemTypeDescription
yearintInteger year (proleptic Gregorian formula).
Return / printbool / textTrue if the year is leap.

Minimal workflow

Pseudocode
function is_leap_year(y):
    return (y mod 4 = 0 and y mod 100 != 0) or (y mod 400 = 0)

Method comparison

MethodIdeaNotes
Boolean one-liner(%4 and not %100) or %400Interview favorite — compact
Nested ifsBranch on %4, then centuriesEasier to explain step by step
calendar.isleapStandard libraryGreat in apps; write it yourself in interviews

⚡ Quick Reference

GoalPattern
Leap predicate(y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
Common yeary % 4 != 0
Century leapy % 400 == 0
Yes classics2024, 2000, 2012
No classics2021, 1900, 2100
Range loopfor y in range(a, b + 1)

📋 One-Liner vs Nested If vs Library

Same Gregorian rule — pick the form that fits the interview.

Boolean
one expression

Compact and easy to memorize

Nested if
step by step

Clearer for whiteboard walkthroughs

calendar
isleap(y)

Prefer in production apps

Interview tip
cite 1900/2000

Shows you know century exceptions

Context

When This Problem Shows Up

Reach for leap-year checks when calendar math and modulus logic appear.

  1. Interview warm-ups

    Boolean logic with a classic real-world rule.

  2. Date validation

    Decide whether February 29 is allowed.

  3. Range listing tasks

    Print leap years in a classroom interval.

  4. After LCM

    Another short divisibility warm-up in this chain.

  5. Not full calendars

    Leap predicate alone is not complete date parsing.

Key benefit: a tiny O(1) check that still forces careful handling of special cases (centuries).

🔮 Live Preview

Check any integer year in JavaScript safe range (|year| ≤ 1,000,000).

Try 2000, 1900, or 2021.

Live result
Press “Check leap”.

Examples Gallery

Three complete Python programs — single-year check for 2024, range 2024–2050, and a nested-if style. Click View Output to reveal sample console results.

📚 Getting Started

One predicate matching the textbook Gregorian rule.

Example 1 — Single Year: 2024

Checks one year with the standard boolean expression.

python
def is_leap_year(year: int) -> bool:
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)


year = 2024
if is_leap_year(year):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

How It Works

2024 is divisible by 4 and not by 100, so the first clause is true. The boolean expression matches the textbook leap rule directly.

⚡ Range Output

Reuse the same helper to filter a year interval.

Example 2 — Leap Years in [2024, 2050]

Prints all leap years in the beginner demo range.

python
def is_leap_year(year: int) -> bool:
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)


start_year = 2024
end_year = 2050

print(f"Leap years in the range {start_year} to {end_year}:")
for y in range(start_year, end_year + 1):
    if is_leap_year(y):
        print(y, end=" ")
print()

How It Works

The pattern is mostly every 4 years. No century year falls inside this interval, so you only see the regular 4-year cadence.

⚙️ Nested-If Style

Same rule, explained branch by branch — great for whiteboards.

Example 3 — Nested Conditions

Checks classics including century years 1900 and 2000.

python
def is_leap_year_nested(year: int) -> bool:
    if year % 4 != 0:
        return False
    if year % 100 != 0:
        return True
    return year % 400 == 0


for value in (2024, 2021, 1900, 2000):
    label = "leap" if is_leap_year_nested(value) else "common"
    print(f"{value}: {label}")

How It Works

First reject years not divisible by 4. Non-century years that pass are leap; century years need the final % 400 test.

🧠 How the Algorithm Decides

1

Check % 4

If year is not divisible by 4, it is common.

Filter
2

Century test

If divisible by 100, require divisible by 400.

Exception
3

Return verdict

True for leap, False for common.

Bool
=

Leap or common

Gregorian predicate complete.

🔎 Worked Walkthrough — Classics

Trace the three modulus checks on famous test years.

Year% 4% 100% 400Result
2024024Leap
20211Common
190000300Common
2000000Leap

Remember: century years need the % 400 override.

Use Cases

Where leap-year checks show up beyond the interview prompt.

1. Interview Warm-Ups

Boolean logic with a memorable real-world rule.

Example: write is_leap_year(y).

2. Date Validation

Allow February 29 only in leap years.

Example: form input for birthdays.

3. Range Filters

List leap years in a classroom interval.

Example: 2024 to 2050 list above.

4. Teaching Modulus

% 4 / % 100 / % 400 drills in one problem.

Example: compare 1900 and 2000.

5. Day Counters

366 vs 365 when summing days in a year.

Example: day-of-year helpers.

6. Calendar Trivia

Explain why century exceptions exist.

Example: average year length ~365.2425.

Pro Tip: recite “divisible by 4, except centuries unless divisible by 400” before coding.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Tiny and Fast

    O(1) time with a few modulus operations.

  2. 2. Famous Test Cases

    2024 / 1900 / 2000 catch most bugs instantly.

  3. 3. Easy to Explain

    One sentence rule maps cleanly to code.

  4. 4. Two Equivalent Styles

    Boolean one-liner or nested ifs — same result.

Pro Tip: lead with the one-liner; switch to nested ifs if the interviewer wants a verbal walkthrough.

Usage Tips

Small habits that keep leap-year solutions interview-ready.

  1. 1. State the Rule First

    Say 4 / 100 / 400 before writing code.

  2. 2. Test 1900 and 2000

    Century pair catches the most common bug.

  3. 3. Prefer Parentheses

    Group and / or so precedence is obvious.

  4. 4. Guard Range Bounds

    Swap or reject when start > end.

  5. 5. Mention Proleptic Scope

    Code applies Gregorian arithmetic uniformly.

Pro Tip: if you forget the century rule, you will call 1900 a leap year — always verify that case.

Common Pitfalls

Mistakes that commonly break leap-year solutions.

  1. 1. Only Checking % 4

    Marks 1900 as leap incorrectly.

    → Always include the 100 / 400 century logic.

  2. 2. Rejecting All Centuries

    Rejecting every % 100 year also rejects 2000.

    → Allow centuries when % 400 == 0.

  3. 3. Operator Precedence Bugs

    Missing parentheses around and / or.

    → Parenthesize the full predicate.

  4. 4. Confusing Calendar Systems

    Assuming Julian rules or local historical quirks.

    → State that this page uses Gregorian arithmetic.

  5. 5. Broken Range Loops

    start > end silently prints nothing.

    → Validate or swap bounds first.

Edge Cases

Leap predicate is only one part of full date validation.

400

Century override

2000 is leap; 1900 is not.

Year systems

Historical vs proleptic

Code usually applies the Gregorian formula uniformly.

Range

start > end

Guard or swap bounds in range loops.

Input

Non-integer year

Reject non-integers in UI / preview parsing.

2100

Future century

2100 is not leap (% 400 != 0).

Negatives

Signed years

Formula still runs; historical meaning differs.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Rule. Leap iff (y%4==0 and y%100!=0) or (y%400==0).
  • Length. Leap years have 366 days; common years have 365.
  • Average. Gregorian mean year length is about 365.2425 days.
  • February. Day 29 exists only in leap years.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 2024, 2000 → leap
  • 2021, 1900 → common

2. Match both styles

  • Boolean vs nested if
  • Assert identical booleans

3. Range 1900 to 2100

  • List all leap years
  • Confirm 1900 missing, 2000 present

4. Count days

  • Return 366 if leap else 365
  • Useful day-of-year helper

Notes

  • Rule: (y%4==0 and y%100!=0) or (y%400==0).
  • Code: one predicate function plus optional range loop.
  • Watch-outs: century years and historical calendar context.
  • Single-year check is O(1); scanning [a, b] is O(b-a+1).

Quick Takeaway: leap if divisible by 4 but not 100, unless also divisible by 400.

⏱️ Time and Space Complexity

TaskTimeExtra space
One year checkO(1)O(1)
Range [a, b]O(b - a + 1)O(1)
Nested-if styleO(1)O(1)

No extra structures needed beyond simple counters.

Wrap Up

🎉 Conclusion

Gregorian leap years follow a short modular rule: divisible by 4, except centuries unless divisible by 400. Encode that as a predicate, test 1900 and 2000, then reuse it for range scans.

Practice the three examples above, then continue to magic numbers for another digit-based warm-up.

2024 and 2000 are leap; 2021 and 1900 are not — memorize those four checks.

💡 Best Practices

✅ Do

  • State the 4 / 100 / 400 rule first
  • Parenthesize the boolean expression
  • Test 2024, 1900, and 2000
  • Reuse one predicate for range scans
  • Mention Gregorian / proleptic scope

❌ Don’t

  • Check only divisible by 4
  • Reject every century year
  • Forget parentheses around and/or
  • Ignore start > end in range loops
  • Confuse Julian and Gregorian rules

Key Takeaways

Knowledge Unlocked

Five things to remember about leap years

Decide leap vs common the interview-friendly way.

5
Core concepts
% 02

Modulus

Three checks

Code
C 03

Century

1900 no / 2000 yes

Edge
29 04

February

Extra day

Calendar
O 05

Cost

O(1) per year

Analysis

❓ Frequently Asked Questions

Leap iff (y%4==0 and y%100!=0) or (y%400==0).
Yes, because it is divisible by 400.
No, divisible by 100 but not by 400.
No. This page uses the usual proleptic Gregorian arithmetic rule.
In code you can still apply the formula to integer years, but historical interpretation differs.
Single-year check is O(1). Range scan is O(b-a+1).
No. Century years need the extra % 400 test — that is why 1900 fails and 2000 passes.
Yes in real projects. Interviews usually want you to write the 4/100/400 predicate yourself.

Did you Know? 🔊

Gregorian reform refined the simple every-4-years rule: century years are not leap years unless divisible by 400.

Continue to Magic Number

Learn how magic numbers repeatedly sum digits until they reach 1.

Magic number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful