Division help in python

Chris Angelico rosuav at gmail.com
Fri Sep 7 09:06:19 EDT 2012


On Fri, Sep 7, 2012 at 10:53 PM, Ramyasri Dodla <ramyasri20 at gmail.com> wrote:
> I am brand new to python. checking over basic stuff. I came across the
> problem while doing so. If any body aware of the problem, kindly respond me.
>
>>>> 5/10
> 0
>>>> - 5/10
> -1
>
> The second case also should yield a 'zero' but it is giving a -1

You're clearly using Python 2, because in Python 3, the / operator
will return a float instead (so these would return 0.5 and -0.5
respectively). But it's helpful to mention what Python version you're
using when you ask for help :)

The reason for this is that / (or in Python 3, //) rounds toward
negative infinity, not toward zero. This allows the modulo operator
(%) to return a positive number, while still maintaining the normal
expectation that:

(x//y)*y + (x%y) == x

for any two integers x and y.

Hope that helps!

ChrisA



More information about the Python-list mailing list