Python: Check Whether a Year is a Leap Year

Document 对象参考手册Python3 Examples

To determine whether a year is a leap year, follow these rules:

  1. If the year is divisible by 4 but not by 100, it is a leap year.
  2. If the year is divisible by 400, it is also a leap year.
  3. 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")

Code explanation:

  1. is_leap_yearThe function takes one parameteryear, which represents the year to be checked.
  2. 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.
  3. If the condition is true, returnTrue, indicating it is a leap year; otherwise, returnFalse。
  4. In the test section, we test whether 2024 is a leap year and output the corresponding message based on the result.

Output:

2024 是闰年

Document 对象参考手册Python3 Examples

Other Extensions