[Tutor] How to test for a remainder from division

Bill Campbell bill at celestial.net
Mon May 14 23:49:55 CEST 2007


On Mon, May 14, 2007, Luke Paireepinart wrote:
>Matt Smith wrote:
>> Hi there,
>>
>> I'm trying to write a short function to test whether a year is a leap
>> year or not. To do this I need to check whether the year divides exactly
>> by 4, 100 and 400. I can't think of an easy way to test whether there is
>> a remainder or not. The best I can come up with so far is:
>>
>> if (year / 4.0) - (year // 4.0) <> 0:
>>
>> This doesn't seem to work, it is always True, is there a problem with
>> the comparison? The arithmetic seems to be the correct way to isolate
>> the remainder of the division.
>>
>> Can anyone suggest a better way of performing this test or alternately,
>> how can I get the line above to work.
>> Matt
>>   
>Matt:  I'm not sure about your pseudocode, but have you tried to 
>accomplish this with the modulus operator?
>It provides the remainder of integer division (i.e. a remainder of 0 
>indicates a perfect divisor.)
>so you could do:
>if year % 4 or year % 100 or year % 400: #then it's divisible perfectly 
>by any of [4,100,400]

While the modulus operator is generally useful for things like
this, one might want to use the calendar module for this if it's
smarter about some of the subtle quirks of leapyear:

import calendar
if calendar.isleap(year): ...

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software, LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

We contend that for a nation to try to tax itself into prosperity is like a
man standing in a bucket and trying to lift himself up by the handle.
    -- Winston Churchill


More information about the Tutor mailing list