Python Program to Check Leap Year

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

In this tutorial, we will learn how to write a Python program to check if a given year is a leap year.

A leap year is a year that is divisible by 4 but not by 100 unless it is also divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. This system ensures that the Gregorian calendar closely matches the solar year.

2. Program Steps

1. Accept or define a year that you wish to check as a leap year.

2. Use conditional statements to check if the year is a leap year following the leap year rules.

3. Print the result of the check.

4. Test the check with a few different years.

3. Code Program

# Function to check if a year is a leap year
def is_leap_year(year):
    # Check if the year is divisible by 4 but not by 100,
    # unless it is also divisible by 400
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

# Test the function
years = [1900, 2000, 2012, 2021]
for y in years:
    if is_leap_year(y):
        print(f"{y} is a leap year.")
    else:
        print(f"{y} is not a leap year.")

Output:

1900 is not a leap year.
2000 is a leap year.
2012 is a leap year.
2021 is not a leap year.

Explanation:

1. The function is_leap_year is defined to determine if the input year is a leap year.

2. The condition checks if year % 4 == 0 (year is divisible by 4) and year % 100 != 0 (year is not divisible by 100), or year % 400 == 0 (year is divisible by 400).

3. If any of the conditions are true, the function returns True, indicating that the year is a leap year; otherwise, it returns False.

4. A list named years contains different years to test the function.

5. A for loop iterates through the years list, calling is_leap_year for each y in the list.

6. The if-else statement within the loop prints out whether each year is a leap year based on the function's return value.

7. The output correctly identifies which of the provided years are leap years based on the defined rules.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare