Leap Year Subroutine

calendar-iconA leap year is a calendar year that contains an additional day (29th of February) added to keep the calendar year synchronised with the astronomical year or seasonal year (which contains roughly 365¼ days or 365.242375 days to be more accurate).

An easy way to work out if a year is a leap year or not is to check if the year (e.g. 2020) is a multiple of 4. If it is, then it is most likely a leap year. Indeed, the rule is slightly more complex than this and can be summarised in three statements:

  • Leap years are any year that can be exactly divided by 4 (such as 2004, 2008, 2012, 2016, 2020, 2024, etc)
  • except if it can be exactly divided by 100, then it isn’t a leap year (such as 2100, 2200, etc)
  • except if it can be exactly divided by 400, then it is a leap year (such as 2000, 2400, 2800, etc)

In Python to work out if a number is a multiple of 4, we can calculate the remainder (MOD) of dividing this number by 4. If this remainder is equal to zero, then the number is a multiple of 4.

Based on this we can create a small function that will take a number (year) as a parameter and return whether the given year is a leap year or not. Here is the flowchart for this function called isLeapYear():
flowchart-leap-year

We can then this function in any program where we need to work out if a year is a leap year or not. For instance, we can create a program that:

  • Asks the user to enter a year (e.g. 2020)
  • Check if the year entered is a leap year or not (using our isLeapYear() function!)
  • Outputs a message to inform the user if the year is a leap year or not.

Here is the flowchart for this program:
isleapyear-flowchart

Video Tutorial


Your Task:


Use Python code to implement both the isLeapYear() function and the main program based on the above flowcharts.

Test Plan:


Once your code is done, complete the following tests to check it is working as expected:

Test # Input Values Expected Output Pass/Fail?
#1 Year: 2020 2020 is a leap year.
It contains 366 days.
#2 Year: 2021 2021 is not a leap year.
It contains 365 days.
#3 Year: 2056 2056 is a leap year.
It contains 366 days.
#4 Year: 2100 2100 is a not a leap year.
It contains 365 days.
#5 Year: 2400 2400 is a leap year.
It contains 366 days.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 23

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: , , ,