For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
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
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
There are 7 different methods to check if a year is a leap year in Python: If-else statement: A simple condition-based approach.Nested if-else: Adds hierarchical logic for conditions.Ternary Operator: A concise single-line implementation.For Loops: Checks the condition in an iterative structure (less commonly used for leap year logic).While Loop: Also iterative, can be used for continuous user input.Python Libraries - calendar.isleap(): A built-in function for checking leap years.Lambda Function: A compact, functional programming approach for leap year verification. If-else statement: A simple condition-based approach. Nested if-else: Adds hierarchical logic for conditions. Ternary Operator: A concise single-line implementation. For Loops: Checks the condition in an iterative structure (less commonly used for leap year logic). While Loop: Also iterative, can be used for continuous user input. Python Libraries - calendar.isleap(): A built-in function for checking leap years. Python Libraries - calendar.isleap () : A built-in function for checking leap years. Lambda Function: A compact, functional programming approach for leap year verification.
The calendar module in Python provides a built-in method calendar.isleap(year), which checks if a given year is a leap year. It returns True if the year is a leap year and False otherwise. The calendar module in Python provides a built-in method calendar.isleap(year) , which checks if a given year is a leap year. It returns True if the year is a leap year and False otherwise. Example: import calendaryear = 2024if calendar.isleap(year): print(f"{year} is a leap year")else: print(f"{year} is not a leap year") import calendar year = 2024 if calendar . isleap ( year ) : print ( f "{year} is a leap year" ) else : print ( f "{year} is not a leap year" ) Advantages: Simplifies the implementation.Highly reliable and optimized for performance.Can be used in scenarios requiring leap year checks in multiple places. Simplifies the implementation. Highly reliable and optimized for performance. Can be used in scenarios requiring leap year checks in multiple places.
The logic is based on the Gregorian calendar rules: 1. A year is a leap year if: It is divisible by 4.But not divisible by 100, unless it is also divisible by 400. It is divisible by 4. But not divisible by 100, unless it is also divisible by 400. 2. Mathematically, the conditions can be expressed as:(year % 4 == 0) and (year % 100 != 0 or year % 400 == 0) Explanation: Years divisible by 4 are typically leap years.However, years divisible by 100 are not leap years (e.g., 1900 is not a leap year).Exception: Years divisible by 400 are leap years (e.g., 2000 is a leap year). Years divisible by 4 are typically leap years. However, years divisible by 100 are not leap years (e.g., 1900 is not a leap year). Exception: Years divisible by 400 are leap years (e.g., 2000 is a leap year).
Advanced techniques for implementing leap year programs include: Lambda Functions: Use a functional programming approach for compact code. is_leap = lambda year: (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)print(is_leap(2024)) is_leap = lambda year : ( year % 4 == 0 ) and ( year % 100 != 0 or year % 400 == 0 ) print ( is_leap ( 2024 ) Using the calendar module:Leverage the built-in isleap() method for reliability and reusability.List Comprehension:Generate a list of leap years from a given range of years. Using the calendar module: Leverage the built-in isleap() method for reliability and reusability. List Comprehension: Generate a list of leap years from a given range of years. leap_years = [year for year in range(2000, 2100) if calendar.isleap(year)]print(leap_years) leap_years = [ year for year in range ( 2000 , 2100 ) if calendar . isleap ( year ) ] print ( leap_years ) Integration with Datetime:Combine leap year checks with other date-related functionalities for robust date validation systems.Handling User Input with While Loops:Use loops to validate user input and re-prompt until valid input is provided. Integration with Datetime: Combine leap year checks with other date-related functionalities for robust date validation systems. Handling User Input with While Loops: Use loops to validate user input and re-prompt until valid input is provided.
A while loop can be used to ensure that the user provides valid input (e.g., a positive integer) for checking leap years. If the input is invalid, the program can re-prompt the user until valid input is provided. Example: while True: try: year = int(input("Enter a year to check if it is a leap year: ")) if year <= 0: print("Year must be a positive integer. Try again.") continue break except ValueError: print("Invalid input. Please enter a valid integer.")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") while True : try : year = int ( input ( "Enter a year to check if it is a leap year: " ) if year <= 0 : print ( "Year must be a positive integer. Try again." ) continue break except ValueError : print ( "Invalid input. Please enter a valid integer." ) 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" ) Advantages: Ensures robust input handling.Prevents crashes due to invalid input (e.g., strings or negative numbers).Enhances user experience by prompting for corrections. Ensures robust input handling. Prevents crashes due to invalid input (e.g., strings or negative numbers). Enhances user experience by prompting for corrections.
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published