Leap Year Checker (Code) in Python

← Back to Projects

Leap Year Checker in Python

About the project: Leap Year Checker project in Python. This will be a self-contained script that allows you to input a year and instantly find out if it is a leap year.

It contains a Python script that uses a loop to let you check multiple years without having to restart the program.

How to use this Calendar Generator:

  • Run the Python script.
  • This Python script is ready for you to use. After you run it, enter a year to check. The program will continue to run until you type 'q' to quit.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# leap_year_checker.py

import sys

def is_leap_year(year):
    """
    Checks if a given year is a leap year.

    Leap year rules:
    - A year is a leap year if it is divisible by 4.
    - However, years divisible by 100 are not leap years,
    - UNLESS they are also divisible by 400.

    Args:
        year (int): The year to check.

    Returns:
        bool: True if the year is a leap year, False otherwise.
    """
    # Using the concise and correct logic
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

def main():
    """Main function to run the Leap Year Checker with a continuous loop."""
    print("--- Python Leap Year Checker ---")
    print("Enter a year to check if it's a leap year (or 'q' to quit).")

    while True:
        try:
            user_input = input("\nEnter a year: ").strip()

            # Check if the user wants to quit
            if user_input.lower() == 'q':
                print("Exiting Leap Year Checker. Goodbye!")
                break
            
            year = int(user_input)
            
            if year <= 0:
                print("Please enter a positive year.")
                continue

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

        except ValueError:
            print("Invalid input. Please enter a valid year as a number.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()