calendar.isleap() function

Leap
Leap in Python
from calendar import isleap

def leap_year(year):
    return isleap(year)
Caution

This approach may be considered a "cheat" for this exercise, which is intended to practice Boolean operators and logic.

The Python standard library includes a calendar module for working with many aspects of dates in the Gregorian calendar.

One of the methods provided is isleap(), which implements exactly the same functionality as this exercise.

This is not a good way to practice the use of Booleans, as the exercise intends. However, it may be convenient (and better tested) if you are working with calendar functions more broadly.

The library function

This is the implementation:

def isleap(year):
    """Return True for leap years, False for non-leap years."""
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

We can see that calendar.isleap() is just syntactic sugar for the boolean-chain approach.

13th Nov 2024 · Found it useful?