
Introductory Python HackerRank - Write a Function that determines if a year is a leap year
Apr 22
2 min read
0
2
0

The Hacker Rank problem is phrased in the following way:
An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
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 is a leap year.
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years
So how do we implement this logic?
The first thing to note is a function is created with the def keyword.
Secondly, the leap variable is initialised as false.
Thirdly, the first limb of the if statement deals with the logic - that is to say if a year is divisible by four (the modulus is = 0), and divisible by a hundred, but not divisible by four hundred then it is not a leap year.
Else if the year is divisible by 4 then it is a leap year.
def is_leap(year):
   leap = False
  Â
   if year % 4 == 0 and year % 100 == 0 and year % 400 != 0:
       leap = False
   elif year % 4 == 0:
       leap = True
  Â
   return leap
Â
year =Â int(input())
print(is_leap(year))