Dividing integers...Convert to float first?

Dan Bishop danb_83 at yahoo.com
Fri Jan 5 21:38:38 EST 2007


On Jan 5, 11:47 am, Thomas Ploch <Thomas.Pl... at gmx.net> wrote:
> Jonathan Smith schrieb:
>
> > Thomas Ploch wrote:
> >> redefined.horiz... at gmail.com schrieb:
> >>> I'm still pretty new to Python. I'm writing a function that accepts
> >>> thre integers as arguments. I need to divide the first integer by te
> >>> second integer, and get a float as a result. I don't want the caller of
> >>> the function to have to pass floats instead of integers. How do I
> >>> convert the arguments passed to the function into floats before I do
> >>> the division? Is this necessary, or is their a better way?
...
> >>>> from __future__ import division
> >>>> 1/2
> > 0.5
>
> > -smithjaahh, I have been tought so many things about python that are actually
> so old, that I am starting to feel embarrassed.

Don't feel embarrassed.  "from __future__ import division" was added to
Python only five years ago, so the tutorial writers haven't had enough
time to mention it yet.

Just remember that it's a good idea to use "from __future__ import
division" (or better, "from __future__ import division as _division")
in every module, and if you really want integer division, use the //
operator instead of /.  This will ensure that your code will continue
to work correctly in Python 3.0, and that you won't be bitten by subtle
bugs like

def mean(num_list):
    return sum(num_list) / len(num_list)




More information about the Python-list mailing list