Table of Contents
Finding Leap Year By Python Programming
What is a leap year?
A leap year is a year that has 366 days instead of the usual 365 days. This happens every four years, except for years that are divisible by 100 but not by 400. For example, the years 2000 and 2004 were leap years, but the years 1700, 1800, and 1900 were not.
Sample leap year:
- 1997 is not a Leap year
- 2000 is a Leap year
- 2019 is not a Leap year
- 2020 is a Leap year
What are the Python Programming knowledge required to understand below example leap year code?
- Operators
- Variables and datatypes
- If Statements
To determine if a year is a leap year in Python, you can use the following code:
# year - Get year from the user ( Integer Variable )
year=int(input("Enter the year:"))
# year divided by 4 then its a leap year
if year%4==0:
print("{ } is a Leap year".format(year))
# year not divided by 4 then its not a leap year
else:
print("{ } is not a Leap year".format(year))
Output:
Enter the year:2020
2020 is a Leap year
This code will first ask the user to enter a year. Then, it will use the is_leap_year() function to check if the year is a leap year. If the year is a leap year, the code will print a message saying so. Otherwise, the code will print a message saying that the year is not a leap year.
To run this code, you will need to have Python installed on your computer. Once you have Python installed, you can save the code above as a .py file and then run it from the command line.
For example, if you save the code as leap_year.py, you can run it by typing the following command into the command line:
Code snippet
python leap_year.py
This will print out whether the year you entered is a leap year or not.
Advantages of using the Python code:
There are several advantages to using the Python code for checking if a year is a leap year. These advantages include:
- The code is very easy to understand and use.
- The code is very efficient and can be easily modified to fit your specific needs.
- The code is open source and can be freely used and modified by anyone.