Write a function that takes in a year and returns ‘True’ or ‘False’ whether that year is a leap year. In the Gregorian calendar, three conditions are used to identify leap years:

  • The year can be evenly divided by 4, is a leap year, unless:
  • The year can be evenly divided by 100, it is NOT a leap year, unless:
  • The year is also evenly divisible by 400. Then it is a leap year.
def is_leap(year):
    leap = False
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                leap = True
        else:
            leap = True
    return leap

Step 1: Declare the function

Since you are asked to write a function, it’s important to do so! Right away you should type ‘def’ and come up with an appropriate name for your function. Since the prompt tells you that the function will be taking in a year, be sure to include one argument in your function declaration that will represent that year.

Step 2: Set variable as ‘False’ by default

Since the majority of years are not leap years, it makes sense to initiate the return value as ‘False’ from the get-go. Doing this prevents you from having to have a lot of unnecessary ‘leap == False’ statements in your code. Only a very specific set of conditions will change leap to ‘True’ and otherwise leap will simply stay as ‘False’.

#software-development #coding-interviews #interview-questions #python #coding

Common Python Coding Interview Questions: Part 5
1.05 GEEK