Python Check Whether a Year Is a Leap Year
To determine whether a year is a leap year, the following rules must be followed:
- 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
Testing
year
=
2024
if
is_leap_year
(
year
)
:
(
f
"{year} is a leap year"
)
else
:
(
f
"{year} is not a leap year"
)
Code analysis:
is_leap_yearThe function takes a parameteryear, represents the year to be judged.if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): This condition checks whether the year is a leap year. First it checks whether the year is divisible by 4 but not by 100, or divisible by 400.- If the condition holds, return
True, indicating it is a leap year; otherwise returnFalse。 - In the test section, we tested whether 2024 is a leap year and output the corresponding information based on the result.
Output result:
2024 是闰年
Python3 Examples