For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
How does Python know if a year is a leap year or not?
Is it just every four years—or is there more to it?
Checking for a leap year seems simple, but it's a fantastic problem for practicing conditional logic in Python. The challenge lies in correctly implementing the rules: a year must be divisible by 4, unless it's a century year, in which case it must also be divisible by 400.
In this step-by-step tutorial, we'll create a leap year program in Python from scratch. You'll learn how to handle user input and write the conditional logic, including how to structure your code as a leap year program in Python using functions. This is a fundamental exercise for any new programmer.
We’ll cover both basic and function-based approaches, making it easy to understand and implement. Want to level up your Python skills? Explore our Data Science Courses and Machine Learning Courses designed for hands-on practice with real-world problems.
Want to level up your Python skills? Explore our Data Science Courses and Machine Learning Courses designed for hands-on practice with real-world problems.
Let’s get started!
A leap year is a year that has an extra day, making it 366 days long instead of the usual 365 days. This additional day is added to February, resulting in February having 29 days instead of 28.
The purpose of leap years is to keep our calendar aligned with the Earth's revolutions around the Sun, which takes approximately 365.2425 days.
To determine whether a year is a leap year, specific divisibility rules must be followed:
Leap Years:
Non-Leap Years:
Looking to bridge the gap between Python practice and actual ML applications? A formal Data Science and Machine Learning course can help you apply these skills to real datasets and industry workflows.
Condition | Result |
Year % 4 == 0 | Potentially a leap year |
Year % 100 == 0 | Check next condition |
Year % 400 == 0 | Confirmed leap year |
Year % 100 == 0 and Year % 400 != 0 | Not a leap year |
1. If-else statement
# Function to check if a year is a leap year using if-else statements
def is_leap_year(year):
# Check if the year is divisible by 4
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True # Year is a leap year
else:
return False # Year is not a leap year
# Example usage
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output:
Enter a year: 2025
2025 is not a leap year.
2. Nested if-else
# Function to check if a year is a leap year using nested if-else statements
def is_leap_year(year):
if year % 4 == 0: # First condition
if year % 100 == 0: # Second condition
if year % 400 == 0: # Third condition
return True # Year is a leap year
else:
return False # Year is not a leap year
else:
return True # Year is a leap year
else:
return False # Year is not a leap year
# Example usage
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output:
Enter a year: 2024
2024 is a leap year.
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
3. Ternary Operator
# Function to check if a year is a leap year using the ternary operator
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example usage
year = int(input("Enter a year: "))
print(f"{year} is {'a leap year' if is_leap_year(year) else 'not a leap year'}.")
Output:
Enter a year: 2023
2023 is not a leap year.
4. For Loops
# Function to check multiple years for leap years using a for loop
def check_multiple_years(start_year, end_year):
print(f"Leap years between {start_year} and {end_year}:")
for year in range(start_year, end_year + 1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year) # Print the leap year
# Example usage
start_year = int(input("Enter the start year: "))
end_year = int(input("Enter the end year: "))
check_multiple_years(start_year, end_year)
Output:
Enter the start year: 1995
Enter the end year: 2025
Leap years between 1995 and 2025:
1996
2000
2004
2008
2012
2016
2020
2024
5. While Loop
# Loop until valid input for the year is provided
while True:
try:
year = int(input("Enter a year: ")) # Request user input
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
break # Exit loop after successful input and processing
except ValueError:
print("Invalid input. Please enter an integer value for the year.")
Output:
Enter a year: 2022
2022 is not a leap year.
6. Python Libraries - calendar.isleap()
import calendar
# Check if the given year is a leap year using the calendar module's isleap function
def check_leap_with_calendar(year):
if calendar.isleap(year):
return True # Year is a leap year
else:
return False # Year is not a leap year
# Example usage
year = int(input("Enter a year: "))
if check_leap_with_calendar(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
# Benefits of Using Built-in Functions:
# - Simplifies code by leveraging Python's built-in functionality.
# - Reduces potential errors by using well-tested library functions.
Output:
Enter a year: 2021
2021 is not a leap year.
7. Lambda Function
# Using lambda function to check for leap years
is_leap_year = lambda year: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example usage
year = int(input("Enter a year: "))
print(f"{year} is {'a leap year' if is_leap_year(year) else 'not a leap year'}.")
Output:
Enter a year: 2020
2020 is a leap year.
Method | Time Complexity | Space Complexity | Analysis |
If-else statement | O(1) | O(1) | Simple conditional check with constant time and space requirements, as no additional memory is used apart from variables. |
Nested if-else | O(1) | O(1) | Similar to the if-else statement; slightly less readable due to the nested structure but with no additional impact on performance. |
Ternary Operator | O(1) | O(1) | Compact and efficient for single-condition checks. Performs exactly like the if-else statement, with the added benefit of concise code. |
For Loop | O(1) | O(1) | Performs similar to if-else but might be considered redundant for this purpose since there’s no iteration over a range. |
While Loop | O(1) | O(1) | Similar to the for loop in terms of complexity. However, it is less practical here since loops are unnecessary for a single-condition check. |
Python Libraries - calendar.isleap() | O(1) | O(1) | Uses the built-in calendar library, optimized for performance. Internally performs the same mathematical checks as a custom implementation. Very efficient and reusable. |
Lambda Function | O(1) | O(1) | Essentially a single-line if-else or ternary operator. Performs the same as an explicit conditional statement but is more concise and fits functional programming paradigms. |
Note: The calendar.isleap() method is the most practical for readability and reusability, especially for production code. The if-else statement or ternary operator is ideal for minimalistic code.
1. Which year is a leap year?
a) 1900
b) 2000
c) 2023
d) 2021
2. How many days are there in a leap year?
a) 364
b) 365
c) 366
d) 367
3. Which condition correctly checks if a year is divisible by 4 in Python?
a) if year / 4 == 0:
b) if year % 4 == 0:
c) if year = 4:
d) if year == 4:
4. Which function can be used to take user input in Python?
a) input()
b) scanf()
c) raw_input()
d) gets()
5. What is the output of 2024 % 100 == 0?
a) True
b) False
c) Error
d) None
6. Which logic checks for leap year correctly?
a) Year divisible by 2
b) Year divisible by 4 but not by 100
c) Year divisible by 10 only
d) Year divisible by 3 and 5
7. What is the correct order of leap year conditions?
a) Divisible by 100 then by 400
b) Divisible by 4 then by 100 but not by 400
c) Divisible by 4 and not by 100, unless divisible by 400
d) Only divisible by 400
8. Which of the following returns True for the year 2000 using a leap year function?
a) is_leap(2000)
b) leap_year(2000)
c) check_leap(2000)
d) All of the above (if defined)
9. You are asked to write a function is_leap(year) to return True or False. What should be its first condition?
a) if year % 4 == 0:
b) if year % 100 == 0:
c) if year % 400 == 0:
d) if year == 0:
10. A user enters the year 2100. Your leap year program returns True. What is likely wrong in the code?
a) It didn’t check divisibility by 100
b) It used input() wrong
c) It missed return statement
d) It used while instead of if
11. You want to write a leap year program using a Python function and take year as input. Which structure is best?
a) def leap():
b) def leap(year):
c) def year(leap):
d) def check():
You've now successfully built a leap year program in Python, mastering the tricky conditional logic that trips up many beginners. This exercise is more than just a simple problem, it's a perfect example of how to translate complex rules into clean, effective code.
By creating a leap year program in Python using functions, you've also learned how to write reusable and organized code, a fundamental skill for any developer. Keep practicing with these kinds of challenges, and you'll be well on your way to tackling even more complex programming problems.
With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Data Science Courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.
By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.
So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.
Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:
Similar Reads: Top Trending Blogs of Python
The logic for a leap year program in Python is based on the rules of the Gregorian calendar, which was designed to keep the calendar year synchronized with the astronomical year. A year is a leap year if it is divisible by 4, except for end-of-century years, which must be divisible by 400. This can be expressed in code as: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0). This logic correctly identifies years like 2024 as leap years (divisible by 4 but not 100) and 2000 as a leap year (divisible by 400), while correctly identifying 1900 as a common year (divisible by 100 but not 400).
The Gregorian calendar was introduced in 1582 to correct for a small inaccuracy in the Julian calendar that preceded it. The Earth's orbit around the sun is approximately 365.2425 days, not exactly 365.25 as the Julian calendar assumed. By skipping leap years on most century years, the Gregorian rule brings the average length of a calendar year much closer to the actual solar year. This historical context is interesting to know when creating a leap year program in Python.
There are several methods to create a leap year program in Python, each with its own advantages. The most common is using a simple if-else statement or a nested if-else to check the conditions. For more concise code, a ternary operator can be used to write the logic in a single line. For the simplest and most reliable solution, you can use the built-in calendar.isleap() function. More advanced techniques include wrapping the logic in a lambda function for a functional approach.
The calendar module in Python provides a built-in, highly optimized function called calendar.isleap(year). This is the most straightforward and recommended method for a leap year program in Python. You simply import the calendar module and then pass the year you want to check to this function. It will return True if the year is a leap year according to the Gregorian rules, and False otherwise. This approach is not only simpler to write but also less prone to logical errors than implementing the conditions manually.
Beyond a simple if-else check, you can use more advanced Python features. A lambda function can define the entire logic in a single, anonymous function: is_leap = lambda year: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0). You can also use a list comprehension to generate a list of all leap years within a specific range, for example: leap_years = [year for year in range(2000, 2100) if calendar.isleap(year)]. This showcases more advanced, "Pythonic" ways to structure your leap year program in Python.
Creating a leap year program in Python using functions is the best practice for writing clean and reusable code. You would define a function, for example check_leap_year(year), that takes the year as a parameter. Inside this function, you would place your conditional logic and return a boolean value (True or False). Your main program can then call this function whenever it needs to check a year. This separates the core logic from the user input and output, making your code much more organized and easier to debug.
A while loop is an excellent tool for ensuring that your leap year program in Python receives valid input from the user. You can wrap your input prompt inside a while True: loop and use a try-except block to catch ValueError if the user enters a non-integer. You can also add a condition to check if the year is a positive number. If the input is valid, you can use the break statement to exit the loop; otherwise, you can print an error message and the loop will continue, re-prompting the user.
Both are used for conditional logic, but they differ in syntax and use case. An if-else statement is a multi-line block that is used to execute different sets of statements based on a condition. A ternary operator, on the other hand, is a single-line expression that evaluates to a value. For a simple leap year program in Python, a ternary operator can be very concise, for example: result = "Leap Year" if is_leap else "Not a Leap Year". However, for more complex logic, a full if-else statement is more readable.
The Gregorian calendar, upon which the leap year rules are based, does not have a year 0; it goes from 1 BC to 1 AD. Therefore, a robust leap year program in Python should treat year 0 (and any negative years) as invalid input. You can add a condition at the beginning of your function, such as if year <= 0:, to handle this edge case and inform the user that the input is out of the valid range.
The time complexity for checking a single year is O(1), which means it takes a constant amount of time, regardless of the value of the year. This is because a leap year program in Python performs a fixed number of simple arithmetic operations (a few modulo checks and logical comparisons). The calculation does not become more complex or take longer for a large year like 2024 versus a smaller year like 4.
While not a standard approach, you could use a dictionary to mimic the conditional logic. For example, you could use a boolean result of a condition as a key to look up the answer. result = {True: "Leap Year", False: "Not a Leap Year"}[(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)] This is a clever but less readable alternative for a leap year program in Python.
To do this, you would start with the given year and use a while loop that continues until a list of N leap years has been collected. Inside the loop, you would check if the current year is a leap year using your leap year logic. If it is, you add it to your list. At the end of each iteration, you increment the year. This is a great way to combine the logic of a leap year program in Python using functions with iterative programming.
A very common mistake is to only check if the year is divisible by 4, completely forgetting the century year rules. Another is to implement the logic incorrectly, for example, using and where an or is needed. Forgetting to handle non-integer or negative inputs is also a frequent oversight. A good leap year program in Python must be logically correct and robust against bad input.
Python's datetime module is fully aware of the leap year rules. If you try to create a date object for a non-existent date, like February 29th of a common year (e.g., datetime.date(2023, 2, 29)), it will raise a ValueError. This is an implicit way to check for a leap year, though using the calendar.isleap() function is more direct.
Leap years were introduced by Julius Caesar in 45 BC with the Julian calendar, which simply added an extra day every four years. This was an oversimplification, and over the centuries, the calendar drifted out of sync with the seasons. The more precise Gregorian calendar, which we use today, was introduced in 1582 to correct this drift by adding the more complex rules about century years. This history is the reason why a leap year program in Python has its specific set of logical conditions.
Thorough testing is crucial. You should test your leap year program in Python with several categories of years. Include a year that is divisible by 4 but not 100 (e.g., 2024), a year that is divisible by 100 but not 400 (e.g., 1900), a year that is divisible by 400 (e.g., 2000), and a year that is not divisible by 4 (e.g., 2023). This will ensure all branches of your conditional logic are working correctly.
Instead of just printing "True" or "False," you can use f-strings to provide a more descriptive and user-friendly output, such as f"{year} is a leap year." or f"{year} is not a leap year.". You can also wrap your main logic in a loop, as shown in a previous question, to allow the user to check multiple years without having to restart the program each time.
The leap year program in Python is a classic beginner project because it is the perfect exercise for practicing fundamental programming concepts. It requires you to use variables, user input, and, most importantly, conditional logic (if-else statements). It's a simple problem with a slightly tricky set of rules, which teaches you the importance of translating detailed requirements into accurate code.
The best way to improve is by combining structured learning with consistent practice. A comprehensive program, like the Python programming courses offered by upGrad, can provide a strong foundation and expert guidance. You should also regularly practice solving problems on coding challenge websites. This will expose you to a wide variety of challenges and help you master the core logic needed to write any leap year program in Python using functions and much more.
The main takeaway is the importance of attention to detail and accurately translating a set of rules into logical code. The leap year program in Python is a perfect example of a problem that seems simple on the surface but has a few crucial edge cases (the century years). It teaches a beginner that successful programming is not just about writing code, but about fully understanding the problem's requirements first.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs