Check Leap Year in Python
Divisible by 4, except centuries, except 400. 1900 is not a leap year. 2000 is.
BeginnerBasic Python ProgramsExample 17 of 25
check-leap-year.py
1# Program to check if a year is a leap year23year = int(input("Enter a year: "))45if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):6 print(year, "is a leap year")7else:8 print(year, "is not a leap year")
Output
Enter a year: 2024 2024 is a leap year
In this one
- 1900 no, 2000 yes, 2024 yes
- check % 400 before % 4
What's going on
The rule people remember: every 4 years. Then they ship a bug for 1900.
divisible by 400 → leap (2000)
else divisible by 100 → not (1900)
else divisible by 4 → leap (2024)
The code checks 400 first, then year % 4 == 0 and year % 100 != 0. Same rule, fewer branches.
2023 is not a leap year. If your program says it is, you only tested % 4.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.