Python Program to Check Leap Year

1. Introduction

A leap year is a year that is divisible by 4, except for end-of-century years, which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. Leap years are a way to ensure that the calendar remains in alignment with the Earth's revolutions around the Sun. Understanding how to determine leap years is fundamental in calendar calculations and is a common problem in programming. This blog post will present a Python program to check if a given year is a leap year, demonstrating basic conditional logic in Python.

2. Program Steps

1. Prompt the user to enter a year.

2. Check if the year is divisible by 4.

3. If the year is a century (divisible by 100), then it must also be divisible by 400 to be a leap year.

4. Based on these conditions, determine if the year is a leap year or not.

5. Display the result to the user.

3. Code Program

# Step 1: Prompt the user to enter a year
year = int(input("Enter a year: "))

# Step 2 & 3: Determine if it's a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    is_leap_year = True
else:
    is_leap_year = False

# Step 5: Display the result
if is_leap_year:
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

Output:
Enter a year: 2000
2000 is a leap year.

Explanation:

1. The program starts by asking the user to input a year. This input is converted into an integer, as year values are numerical.

2. To determine if the year is a leap year, the program checks two conditions: First, the year must be divisible by 4 but not by 100; Second, if the year is a century (divisible by 100), it must also be divisible by 400. These conditions are based on the rules that govern leap years.

3. These checks are performed using a combination of conditional statements (if, and, or) to evaluate the divisibility of the year by 4, 100, and 400.

4. The result of these checks is stored in the boolean variable is_leap_year.

5. Finally, the program prints whether the entered year is a leap year or not, providing a clear, user-friendly output. This example demonstrates how to implement conditional logic in Python to solve a practical problem.


Comments