Newbie: can't devide by function()

Jeff Epler jepler at unpythonic.net
Mon Mar 24 12:26:21 EST 2003


In current versions of Python, when you divide an integer by another
integer, the result is another integer.  You must force the type of one
operand to be float so that the result is float.
    >>> 2 / 3
    0
    >>> 2 * 1.0 / 3
    .666666666666666663
    >>> float(2) / 3
    .666666666666666663

You can also do this in some versions of Python (2.2 and newer):
    >>> from __future__ import division
    >>> 2 / 3
    0.66666666666666663
    >>> 2 // 3
    0
I don't recommend it, since it will surprise people reading your code
who know the usual definition of /.

Jeff





More information about the Python-list mailing list