Practice: Leap Year

Practice: Leap Year

This exercise combines and, or, not, and the modulo operator from First Steps.

A year is a leap year when:

  • it is divisible by 4,
  • except years divisible by 100, which are not leap years,
  • except years divisible by 400, which are.

So 2024 is a leap year, 1900 is not, and 2000 is.

Recall from First Steps: year % 4 == 0 is True exactly when year is divisible by 4.

Exercise

  1. Define a function named is_leap_year with one parameter, year.
  2. Return True when year is a leap year, otherwise False.

Run your code to see the output, then press Submit.

Hints

  • Write the three rules as three boolean expressions first, in separate variables if it helps.
  • One correct shape: divisible by 400, or divisible by 4 and not divisible by 100.
  • Test your function against all three example years before submitting.

Tests

import unittest


class TestIsLeapYear(unittest.TestCase):
    def test_2024_is_a_leap_year(self):
        self.assertIs(is_leap_year(2024), True)

    def test_2023_is_not_a_leap_year(self):
        self.assertIs(is_leap_year(2023), False)

    def test_1900_is_not_a_leap_year(self):
        self.assertIs(is_leap_year(1900), False)

    def test_2000_is_a_leap_year(self):
        self.assertIs(is_leap_year(2000), True)

    def test_2100_is_not_a_leap_year(self):
        self.assertIs(is_leap_year(2100), False)
def is_leap_year(year):
    return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)


print(is_leap_year(2024))
print(is_leap_year(1900))
print(is_leap_year(2000))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.