Working with a remainder of Zero with modulo operation?
I'm having some difficulty working with a remainder of zero with the modulo operator.
Basically this is a line of my 开发者_JAVA百科code
fday= (day+24) % 30
I'm trying to just add 24 to any day and take the remainder of it. However, if a user enters 6 for the day, the result is zero which I don't want.
How can I make the operation return 6 if 6 is entered? Is there a better way to do this?
Update:
I'm trying to take a previously defined variable (day
) and add 24 days to that value.
However if a user enters the 25th day of the month, and then I add 24 to it I get 49, but 49 days arent in a month.
That's why I'm trying to use the modulo operation to give me the remainder instead, because it works for the 30 days in one month thing.
Another example:
If 5 was input, it would be 5 +24 which is 29 and then 29%30 = 29
. So 5 works for what I'm trying to do (which is to just add 24 days to the value and still keep the output under 30 (because there are only 30 days in a month for the purposes of what I'm doing).
You say in the comments that for 5
you want 29
, for 6
you want 6
, and for 7
you want 1
. That doesn't make sense. The correct value for 6
is 30
not 6
or 0
when you're calculating a day modulo 30
.
In math, division by 30
gives a remainder between 0
and 29
-- that's what modulo 30
is. What you want is a number between 1
and 30
.
So you need to take the day, subtract 1
(to get a day between 0
and 29
instead of 1
and 30
), add 24
, then do the modulo 30
, then add 1
(to get back a day between 1
and 30
.
result = ((day - 1 + 24) % 30) + 1
That way you'll always get the correct number between 1
and 30
and you don't have to think of 6
as a special case.
Consider using the functionality in the datetime
module instead of trying to reinvent it:
>>> from datetime import date, timedelta
>>> for month in (4, 5):
... for day in (5, 6, 7, 8):
... start = date(2011, month, day)
... later = start + timedelta(days=24)
... print str(start), str(later)
...
2011-04-05 2011-04-29
2011-04-06 2011-04-30
2011-04-07 2011-05-01
2011-04-08 2011-05-02
2011-05-05 2011-05-29
2011-05-06 2011-05-30
2011-05-07 2011-05-31
2011-05-08 2011-06-01
精彩评论