Python Program to Check if Year is Leap Year
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0): to test the leap year conditions.Examples
How to Think About It
Algorithm
Code
year = int(input("Enter a year: ")) if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0): print(f"{year} is a leap year") else: print(f"{year} is not a leap year")
Dry Run
Let's trace the year 1900 through the code
Input year
year = 1900
Check divisible by 400
1900 % 400 == 300 (False)
Check divisible by 4 and not by 100
1900 % 4 == 0 (True) and 1900 % 100 == 0 (True), so condition is False
Result
Print '1900 is not a leap year'
| Step | Condition | Result |
|---|---|---|
| Divisible by 400 | 1900 % 400 == 0 | False |
| Divisible by 4 and not 100 | 1900 % 4 == 0 and 1900 % 100 != 0 | False |
Why This Works
Step 1: Divisible by 400 means leap year
If a year divides evenly by 400, it is always a leap year, so we check year % 400 == 0 first.
Step 2: Divisible by 4 but not by 100 means leap year
If the year is divisible by 4 but not by 100, it is a leap year, checked by year % 4 == 0 and year % 100 != 0.
Step 3: Otherwise, not a leap year
If neither condition is true, the year is not a leap year.
Alternative Approaches
import calendar year = int(input("Enter a year: ")) if calendar.isleap(year): print(f"{year} is a leap year") else: print(f"{year} is not a leap year")
def is_leap_year(year): return (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0) 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")
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic and logical operations regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables are used, and no extra data structures are created, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time, but using the calendar module adds a small overhead due to import, while the direct arithmetic check is fastest and simplest.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct arithmetic check | O(1) | O(1) | Simple and fast checks without imports |
| calendar.isleap() function | O(1) | O(1) | Using built-in library for readability |
| Function wrapper | O(1) | O(1) | Reusable code and clarity |