A CHALLENGE ON HOW TO DETERMINE IF A GIVEN YEAR IS A LEAP YEAR IN PYTHON:
This is one of the popular code challenge questions you will see on some popular tech recruiting websites like hackerank, coderbyte and etc. It’s used most times to test your beginner/intermediate python skills.
Without further ado, let’s dive into the problem solving for this challenge. My assumptions are that you already have a beginner or intermediate level of experience in python programming.
Firstly before you solve a challenge you’d need to understand all the concepts used in the question. The basic concept here is leap year. So what is a leap year? If you don’t know this already, do yourself a favor and have a look at the wikipedia’s definition of a leap year here.
So I presume you now know what a leap year is. So basically the conditions of a leap is as follows:
- The year can be evenly divided by 4
- If the year can be evenly divided by 100, it is not a leap year unless the year is also evenly divisible by 400, then it’s a leap year.
In essence, any valid leap year must meet the aforementioned conditions above. So our task is clear now:
We are to write a function that takes a year as an input, which will become an integer, then check if the year meets all the conditions of a leap year. If it does or does not meet all the conditions then we will return a boolean response(True or False) accordingly.
WRITING THE FUNCTION TO CALCULATE LEAP YEAR IN PYTHON:
#get the year from user
year = int(input('Enter year:\n'))
answer = False
#all the conditions goes into the conditions variable
conditions = [year % 4 == 0, year % 400 == 0 or year % 100 != 0]
answer = True
According to the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. So you can confirm with the check_leap function.
For instance when you run the function for year 2400 you will get the following output:
CODE EXPLANATION: There isn’t much to explain here, we got the user input and converted to an int type the same time, we know the input function returns a string so we needed to convert to an integer.
Then we created a boolean type variable called answer and gave it False value which will only become True when the leap year conditions are fully met.
Then instead of repeating ourselves with if statements, we decided to put all conditions inside a list called conditions, and now use only one if statement. Pretty simple right?
That’s it! You will never fail that leap year in python code challenge again.
If you have any questions on this tutorial, please don’t hesitate to ask me in the comment section or write me directly. To also see more codes/tutorials similar to calculating leap year in python, kindly check our tutorial post page.