Python: Check Whether a Year is a Leap Year
To determine whether a year is a leap year, follow these rules:
- If the year is divisible by 4 but not by 100, it is a leap year.
- If the year is divisible by 400, it is also a leap year.
- Otherwise, it is not a leap year.
Example
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Test
year = 2024
if is_leap_year(year):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Test
year = 2024
if is_leap_year(year):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Code explanation:
is_leap_yearThe function takes one parameteryear, which represents the year to be checked.if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): This condition determines whether the year is a leap year. It first checks whether the year is divisible by 4 but not by 100, or divisible by 400.- If the condition is true, return
True, indicating it is a leap year; otherwise, returnFalse。 - In the test section, we test whether 2024 is a leap year and output the corresponding message based on the result.
Output:
2024 是闰年Other Extensions
Python3 Examples