Write a Python Program to Generate The Next 15 Leap Years Starting From a Given Year. Populate The Leap Years Into a List And Display The List

In this article we will be solving python program to generate the next 15 leap years starting from a given year, add the leap years in to python list and then print it.

Before going to the program lets understand the leap year, a leap year is the year that has extra day in February month i.e, 29. The number of days in leap year will be 366. To check if the number is leap year or not we need to perform modulus operation as below.

(number % 4 == 0 and number % 100 != 0) or (number % 400 == 0)

If number is completely divisible by 4 and mot by 100 or completely divisible by 400 it is said to be leap year. Now lets get in to program.


leap year



This program can be divided in to three phases


Phase 1 : Ask user to enter a year, convert the year to integer once you get from the input function call and check if year is non negative. If non negative exit the program.

year = int(input("Enter Year : "))
if year < 0:
    print("Invalid Year: Year cannot be negative number !")
    exit(1)



Phase 2 : Create an empty list and use while loop to check if list length is less than 15. Until while loop is false check if the year leap year using if statement, if true add it to the list and increment the year.

years_list = []
while len(years_list) < 15:
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        years_list.append(year)
    year += 1

 

 

Phase 3 : Display the list, now the years_list will contain the 15 leap years finally print the items in the list using for loop.

for item in years_list:
    print(item)

 

Final Program : Below is the final version of code, with some runs.

year = int(input("Enter Year : "))
if year < 0:
    print("Invalid Year: Year cannot be negative number !")
    exit(1)

years_list = []
while len(years_list) < 15:
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        years_list.append(year)
    year += 1

for item in years_list:
    print(item)



Run 1 : Providing negative number to program
# python leap.py
Enter Year : -5
Invalid Year: Year cannot be negative number !



Run 2 : Giving input year as 2000
# python leap.py
Enter Year : 2000
2000
2004
2008
2012
2016
2020
2024
2028
2032
2036
2040
2044
2048
2052
2056



Run 3 : Giving input year as 4
# python leap.py
Enter Year : 4
4
8
12
16
20
24
28
32
36
40
44
48
52
56
60


Conclusion : Hope you enjoyed reading this article. Subscribe to my channel and blog for more articles.

 

Keywords : 

Write a Python Program to Generate The Next 15 Leap Years Starting From a Given Year. Populate The Leap Years Into a List And Display The List

Post a Comment

0 Comments