EnthusiasticGerbil
EnthusiasticGerbil

Reputation: 21

Python 2: why does this function follow with a boolean without if/else conditions?

Here is the sample code I was given to complete:

def is_leap(year):
leap = False

year = int(raw_input())
print is_leap(year)

I've managed to solve it through all sample test cases but I don't understand why leap is assigned False when there are no conditions. What is the point of doing that if I have to redefine leap to True or False again based on the conditions?

Conditions: A year is considered a leap year when:

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.

My code:

def is_leap(year):
    leap = False

    if (year % 4 == 0):
       leap = True
    if year % 100 == 0:
        if year % 400 == 0:
            leap = True
        else:
            leap = False
    return leap
year = int(raw_input())
print is_leap(year)

Upvotes: 2

Views: 97

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308530

You have two if statements that can set the leap variable. But it's completely possible that neither condition will be met, and leap needs to have a value in that case or you will get an exception in the return statement.

P.S. No need to make the question specific to Python 2, it's the same in Python 3.

Upvotes: 1

Related Questions