Leap Year Checker Program in Python

This document provides a Python program to determine whether a given year is a leap year. A leap year is a year that is divisible by 4, but years divisible by 100 are not leap years unless they are also divisible by 400.

Program Structure

The program follows these steps:

  1. Accepts a year as input from the user.
  2. Checks if the year is divisible by 4.
  3. If the year is divisible by 4, further checks if it is also divisible by 100.
  4. If the year is divisible by 100, checks if it is also divisible by 400.
  5. Prints whether the year is a leap year or not based on the conditions.

Python Code


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

    A year is a leap year if:
    - It is divisible by 4, and
    - It is not divisible by 100, unless
    - It is also divisible by 400.

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

    Returns:
    bool: True if the year is a leap year, False otherwise.
    """
    if (year % 4 == 0):
        if (year % 100 == 0):
            if (year % 400 == 0):
                return True
            else:
                return False
        else:
            return True
    else:
        return False

def main():
    """
    Main function to execute the leap year checker.
    """
    try:
        year = int(input("Enter a year: "))
        if is_leap_year(year):
            print(f"{year} is a leap year.")
        else:
            print(f"{year} is not a leap year.")
    except ValueError:
        print("Please enter a valid integer year.")

if __name__ == "__main__":
    main()
    

Explanation

The is_leap_year function implements the leap year logic:

  • If a year is divisible by 4, it’s a potential leap year.
  • If it’s also divisible by 100, it must be divisible by 400 to be a leap year.
  • Otherwise, it’s not a leap year.

The main function handles user input and output:

  • It prompts the user to enter a year.
  • It calls the is_leap_year function and prints whether the year is a leap year.
  • It includes error handling for invalid input.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)