35. Leap year
Most years have 365 days, but a leap year has 366: February gets a 29th day. Which years are leap years follows a rule in three parts:
- a year that divides evenly by 4 is a leap year,
- except a year that divides evenly by 100, which isn't,
- except a year that divides evenly by 400, which is after all.
So 2024 is a leap year, 1900 isn't (it divides by 100), and 2000 is (it divides by 400).
Write a function is_leap(year) that takes a whole number year and returns True if it is a leap year, or False
if it isn't.
Example 1
year = 2024TrueExample 2
year = 1900FalseExample 3
year = 2000TrueConstraints
yearis a whole number from 1 to 9999.
Submit also runs 9 more tests you can't see.
Practises Booleans and Comparisons (lesson 7).
year % 4 == 0isTruewhen 4 dividesyearevenly:%gives the remainder of the division.- The first two parts make one condition: divisible by 4 and not by 100. Write it with
andand!=(ornot). - Join that with the third part using
or:(year % 4 == 0 and year % 100 != 0) or year % 400 == 0. Check it with 1900, which must beFalse, and 2000, which must beTrue.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def is_leap(year):
"""Check whether a year is a leap year.
year: int, from 1 to 9999
Returns: bool, True for a leap year, else False
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.