Leap year

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Sep 28 08:22:16 CEST 2014


Seymore4Head wrote:

> Still practicing.  Since this is listed as a Pseudocode, I assume this
> is a good way to explain something.  That means I can also assume my
> logic is fading with age.
> http://en.wikipedia.org/wiki/Leap_year#Algorithm
> 
> Me trying to look at the algorithm, it would lead me to try something
> like:
> if year % 4 !=0:
>       return False
> elif year % 100 !=0:
>       return True
> elif year % 400 !=0:
>       return False

You can only have the "return" statement inside a function, not in top-level
code, and that looks like top-level code. So you need to start with
something like:

def is_leapyear(year):
    if year % 4 != 0:
        return False
    ...


> ****   Since it is a practice problem I have the answer:
> def is_leap_year(year):
>     return ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0))

Or in English:

- years which are divisible by 4 are leap years, *unless* they are also
divisible by 100, in which case they aren't leap years, *except* that years
divisible by 400 are leap years.

Converting to Python code:

def is_leap_year(year):
    return (
        # Years which are divisible by 4
        (year % 4 == 0)
        # and not divisible by 100
        and (year % 100 != 0)
        # unless divisible by 400
        or (year % 400 == 0)
        )


> I didn't have any problem when I did this:
> 
> if year % 400 == 0:
>       print ("Not leap year")
> elif year % 100 == 0:
>       print ("Leap year")
> elif year % 4 == 0:
>       print ("Leap year")
> else:
>       print ("Not leap year")

You might not have had any problems, but neither did you get the right
answers. According to your code, 2000 is not a leap year (since 2000 % 400
equals 0) but in reality it is. On the other hand, your code says 1900 was
a leap year, which it was not.

The lesson here is, code isn't working until you've actually tested it, and
to test it sufficiently you need to check the corner cases, not just the
obvious ones.



-- 
Steven




More information about the Python-list mailing list