1. Introduction
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.
Comments
Post a Comment
Leave Comment