In this article we will show you how to create a program in python to check if a year is a leap year.
First of all lets see a definition of a leap year
A leap year is a calendar year that contains an additional day added to keep the calendar year synchronized with the astronomical year or seasonal year.
For example, in the Gregorian calendar, each leap year has 366 days instead of 365, by extending February to 29 days rather than the common 28. These extra days occur in each year which is an integer multiple of 4 (except for years evenly divisible by 100, but not by 400).
How to determine whether a year is a leap year
To determine whether a year is a leap year, you can follow these 5 steps:
- If the year is evenly divisible by 4 then go to step 2. Otherwise, go to step 5.
- If the year is evenly divisible by 100 then go to step 3. Otherwise, go to step 4.
- If the year is evenly divisible by 400 then go to step 4. Otherwise, go to step 5.
- The year is a leap year
- The year is not a leap year
Now lets see an example of how to do this in python
Example
Save the following example as checkleapyear.py, I use thonny
# Default function to implement conditions to check leap year def CheckLeapYear(Year): # Check the year is leap year if((Year % 400 == 0) or (Year % 100 != 0) and (Year % 4 == 0)): print("The Year is a leap Year"); # it is not a leap year else: print ("The Year is not a leap Year") # Get the year from user Year = int(input("Enter the year to check: ")) # Print result CheckLeapYear(Year)
Lets see a couple of runs
>>> %Run checkleapyear.py
Enter the year to check: 2000
The Year is a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 1970
The Year is not a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 1700
The Year is not a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 2012
The Year is a leap Year
Link
Here is the code in our github repo
https://github.com/programmershelp/maxpython/blob/main/code%20example/checkleapyear.py