leap_year.py
= int(input("Enter a year: "))
year
if year % 4 == 0:
print(year, "is a leap year")
Whenever solving a problem like this, it’s always good to build it up one step at a time. You could be tempted to jump right to the solution but it is easier to take small steps and check your results along the way than debugging a long piece of code.
The first step is to implement the simplest of the logical checks: is the year divisible by \(4\)? If it is, print out an appropriate message:
leap_year.py
= int(input("Enter a year: "))
year
if year % 4 == 0:
print(year, "is a leap year")
and check that it works for a know leap year.
Terminal/Command Prompt
python leap_year.py
Enter a year: 2024
2024 is a leap year
For a year that we know is not a leap year, what do we get:
Enter a year: 2023
We get no output, so let’s fix that next, by adding an else
:
leap_year.py
= int(input("Enter a year: "))
year
if year % 4 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Enter a year: 2023
2023 is not a leap year
So far it’s looking like it’s doing the right thing. We have a working leap year calculator which covers most cases correctly.
Let’s check the next corner case: what happens if the year is divisible by 100. The rules say that this should not be a leap year:
Enter a year: 1900
1900 is a leap year
So it’s currently getting this wrong. We need to add in a check to see if the year is divisible by 100 and set it to be labelled as not a leap year.
Here we need to be careful as any number which is divisible by 100 is also divisible by 4 but we want a special thing to happen in the former case. The divisible-by-100 check is more specific than the divisible-by\(4\) check, so it must come first in the if
-elif
-else
chain:
leap_year.py
= int(input("Enter a year: "))
year
if year % 100 == 0:
print(year, "is not a leap year")
elif year % 4 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Enter a year: 2024
2024 is a leap year
Enter a year: 2023
2023 is not a leap year
Enter a year: 1900
1900 is not a leap year
The code is working for all those cases correctly, however, the last condition to think about is what happens for the year 2000:
Enter a year: 2000
2000 is not a leap year
This year should be a leap year as it is divisible by 400. Again this is more specific than the previous two so must be added before them in the chain:
leap_year.py
= int(input("Enter a year: "))
year
if year % 400 == 0:
print(year, "is a leap year")
elif year % 100 == 0:
print(year, "is not a leap year")
elif year % 4 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Enter a year: 2024
2024 is a leap year
Enter a year: 2023
2023 is not a leap year
Enter a year: 1900
1900 is not a leap year
Enter a year: 2000
2000 is a leap year