Leap Year Program in Python

In the previous article we have seen the programs and logic relating to figuring out the largest of three numbers provided by user, in this article we will look at how to implement Leap Year logic in Python. Leap year is the year in which an additional day exists in February, and occurs about every 4 years. Before we look at the Leap Year program in Python and it’s appropriate logic let us try to solve a common puzzle/riddle.

Leap Year problem

Two people are born in the same year in 1948. In 2020, one person celebrates 72th Birthday but the other celebrates their 18th Birthday. How is this possible?

The answer to this common puzzle is that the second person was born on Feb 29th of 1948 (which was a leap year) and has hence celebrated their birthday only during the leap years. In reality, people who are born on 29th Feb of a Leap year often choose to celebrate their birthday on Feb 28th or March 1st rather than waiting for a leap year to celebrate it. But for the sake of furthering our understanding we have ignored that particular practical aspect.

So how do we decide whether a given year is a leap year or not? There are two rules by which we have to adhere to determine whether a given year is a leap year.

Rule 1: Multiple of 4 but not a multiple of 100
Ex: 1948, 1952, 1956, 1960 and so on…..

Rule 2: It is a Multiple of 400
Rule 2 implies that there are some possible exceptions to the exclusion of multiples of 100 in the first rule.
Ex:1200, 1600, 2000, 2400, and so on…..
Note: Years like 2100, 2200, 2300, 2500 are NOT Loop.

Implementation of Leap Year program in Python

y = int(input("Enter Year"))
if y%4 == 0 and y%100 != 0:
    print("Yes")   # Rule 1
elif y%400 == 0:
    print("Yes") # Rule 2
else:
print("No")
Output:
Enter Year: 2012
Yes
Enter Year: 2019
No

In the above program we check the condition of the loop year by the consideration of whether it is a multiple of 4, alongside with ensuring that the year is not a multiple of 100 which is to satisfy the first rule. If it fails this condition, to account for the second rule we also ensure whether or not the year given happens to be a multiple of 400. If either of the conditions based on the rule provisions are correct we obtain a “Yes”, in any other condition we obtain a “No”.

Thus, we have gone through the implementation of Leap Year program in Python, in the next subsequent article we will explore the implementation of a calculator in Python.

Leave a Comment