Write a function that determines whether a year is a leap year.
is_leap_year(year)
The rule: a year is a leap year if it's divisible by 4, except century years (divisible by 100), which are only leap years if they're also divisible by 400.
is_leap_year(2024) // → True (divisible by 4, not a century year)
is_leap_year(2023) // → False (not divisible by 4)
is_leap_year(1900) // → False (century year, not divisible by 400)
is_leap_year(2000) // → True (century year, divisible by 400)
This is the classic example of a rule that looks simple ("divisible by 4") but has a documented exception, then an exception to the exception. Turning it into a single boolean expression is good practice at combining and/or/not.
Break the rule into pieces:
year % 4 == 0Put together:
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Read it as: "divisible by 4, and (either it's not a century year, or it's specifically divisible by 400)". The parentheses around (year % 100 != 0 or year % 400 == 0) matter — without them, Python's operator precedence would group and before or differently, changing the meaning entirely.
Check it against the tricky cases: 1900 is divisible by 4 and by 100, but not by 400 — year % 100 != 0 is False and year % 400 == 0 is also False, so the whole or is False, and the year isn't a leap year. 2000 is divisible by 4, by 100, and by 400 — the or clause is True because of the 400 check, so it is.
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.