Python Code Example: check leap year in if else statement

A normal year has 365 days. Every four years, however, there is a leap year with 366 days. This is because the earth does not need exactly 365 days to travel once around the sun, but about a quarter day more. So a year has one day more every 4 years.

So that the calculation is correct, there is no leap year every 100 years. Nevertheless, every four hundred years a leap year takes place. This concerns the years 2000, 2400 etc.

Code Explanation

This code defines a function isLeapYear(year) that determines whether a given year is a leap year or not.

The function uses an if statement with multiple elif clauses to evaluate the year and determine if it’s a leap year.

Here’s how the function works:

  1. The first if clause checks if the year is not evenly divisible by 4 (year % 4 != 0). If the year is not evenly divisible by 4, it returns False immediately, indicating that it’s not a leap year.
  2. If the year is evenly divisible by 4, the function moves on to the next elif clause, which checks if the year is evenly divisible by 400 (year % 400 == 0). If the year is evenly divisible by 400, it returns True, indicating that it’s a leap year.
  3. If the year is not evenly divisible by 400, the function moves on to the next elif clause, which checks if the year is evenly divisible by 100 (year % 100 == 0). If the year is evenly divisible by 100, it returns False, indicating that it’s not a leap year.
  4. If none of the above conditions are met, the function returns True in the final else clause, indicating that it’s a leap year.

The code then calls the isLeapYear function with the year 2020, and if the function returns True, it prints 2020 is a leap year. If the function returns False, it prints 2020 is not a leap year.

def isLeapYear(year):
    if (year % 4 != 0):
        return False
    elif (year % 400 == 0):
        return True
    elif (year % 100 == 0):
        return False
    else:
        return True


year = 2020

if(isLeapYear(year)):
    print(str(year) + " is a leap year")
else:
    print(str(year) + " is not a leap year")
Output
2020 is a leap year