Leap Years
A leap year is a year that has 366 days instead of 365 days. This is done to keep our calendars in sync with the Earth’s orbit around the Sun. The Earth takes about 365.24 days to orbit the Sun, so we add an extra day to the calendar every four years to make up for the difference.
How to check if a year is a leap year
There are a few rules for checking if a year is a leap year:
- A year is a leap year if it is divisible by 4.
- However, a century year (ending in 00) is not a leap year unless it is also divisible by 400.
Python code for finding leap years
def leap_years(start_year, end_year):
This line defines a function called leap_years()
which takes two arguments: start_year
and end_year
.
The function will return a list of leap years between the range of years given.
leap_years = []
This line creates an empty list called leap_years
. This list will be used to store the leap years that the function finds.
for year in range(start_year, end_year + 1):
This line starts a for loop that iterates over the range of years from start_year
to end_year
, inclusive.
The function range
stops before the second argument, so we add 1 to end_year
to make sure the loop includes it.
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
This line checks if the current year is a leap year. A year is a leap year if it is divisible by 4, but not divisible by 100, or if it is divisible by 400.
If the current year satisfies either of these conditions, then the function will add it to the leap_years
list.
leap_years.append(year)
This line adds the current year to the leap_years
list.
return leap_years
This line returns the leap_years
list.
print(leap_years(2000, 2030))
This line prints the output of the leap_years()
function, which is a list of leap years between 2000 and 2030, inclusive.
Here is an example of the output of the code:
[2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028]
Conclusion
Understanding the logic behind identifying leap years and encapsulating that logic within a Python function is not only a practical programming exercise but also a fascinating exploration into the synchronizations between our calendar and astronomical cycles. This brief code exploration provides beginners and enthusiasts a window into the realm of conditional logic, loops, and functions in Python, all while exploring an intriguing real-world application.
Here is the source code on GitHub :