Zed-King Institute

    Python Program to Check Leap Year

    easyif / elsePython

    Leap year looks simple but has a trap — century years. That is exactly why examiners like it.

    The question

    Read a year and print Leap year or Not a leap year. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.

    The code

    program.py

    y = int(input())
    if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
        print("Leap year")
    else:
        print("Not a leap year")

    Input

    1996

    Output

    Leap year

    How it works

    1. 1A year divisible by 4 is usually a leap year…
    2. 2…except century years (divisible by 100), which are not…
    3. 3…unless they are also divisible by 400. So 2000 is a leap year but 1900 is not.
    4. 4All three rules fit in one condition: (y % 4 == 0 and y % 100 != 0) or y % 400 == 0.

    Common mistakes

    • Checking only y % 4 == 0 — it wrongly calls 1900 and 2100 leap years.
    • Missing brackets around the and part, which makes the condition hard to read and easy to break.

    Leap year program using nested if

    The three rules written one inside the other, in the order you would say them aloud. Longer, but easy to explain in a viva.

    program.py

    y = int(input())
    if y % 4 == 0:
        if y % 100 == 0:
            if y % 400 == 0:
                print("Leap year")
            else:
                print("Not a leap year")
        else:
            print("Leap year")
    else:
        print("Not a leap year")

    Input

    1900

    Output

    Not a leap year

    Leap year using the calendar module

    Python already knows the rule: calendar.isleap() returns True or False. Fine for real programs; in an exam, write the condition yourself unless the question allows a module.

    program.py

    import calendar
    
    y = int(input())
    if calendar.isleap(y):
        print("Leap year")
    else:
        print("Not a leap year")

    Input

    2000

    Output

    Leap year

    Questions students ask

    What is the condition for a leap year in Python?
    (y % 4 == 0 and y % 100 != 0) or y % 400 == 0. A year is a leap year when it divides by 4 but not by 100, or when it divides by 400.
    Is 1900 a leap year? Is 2000?
    1900 is not: it divides by 100 but not by 400. 2000 is: it divides by 400. 2024 and 2028 are leap years; 2100 will not be.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    Preparing for NIELIT O Level?

    This program is the kind asked in the M3 (Python) theory paper and the PR-3 practical exam.

    More in if / else