Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Year Is a Leap Year

Python Check Whether a Year Is a Leap Year

Document Object Reference Manual Python3 Examples

To determine whether a year is a leap year, the following rules must be followed:

  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

Testing

year

=

2024

if

is_leap_year

(

year

)

:

   

print

(

f

"{year} is a leap year"

)

else

:

   

print

(

f

"{year} is not a leap year"

)

Code analysis:

  1. is_leap_year The function takes a parameter year, represents the year to be judged.
  2. 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.
  3. If the condition holds, return True, indicating it is a leap year; otherwise return False。
  4. In the test section, we tested whether 2024 is a leap year and output the corresponding information based on the result.

Output result:

2024 是闰年

Document Object Reference Manual Python3 Examples