Dividing integers...Convert to float first?

Beliavsky beliavsky at aol.com
Fri Jan 5 21:20:50 EST 2007


Thomas Ploch wrote:
> Jonathan Smith schrieb:
> > Thomas Ploch wrote:
> >> redefined.horizons 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?
> >>>
> >>> Thanks,
> >>>
> >>> Scott Huey
> >>>
> >>
> >> Yes, it is necessary. If you divide two integers, the result will be an
> >> integer.
> >>
> >>  >>> 1/2
> >>  0
> >>
> >> You need the function float() -> float because a division between
> >> integers and floats will have floats as their results
> >>
> >>  >>> float(1)/2
> >>  0.5
> >
> >
> >>>> from __future__ import division
> >>>> 1/2
> > 0.5
> >
> > -smithj
> >
>
> aahh, I have been tought so many things about python that are actually
> so old, that I am starting to feel embarrassed.
>
> That brings me to the point, that learning a language X at university
> always brings you to a point where you know (almost) everything, but in
> reality know nothing because course material is too old...

If you learned C or Fortran 10 years ago, the constructs you learned
still have the same meaning, even though new features have been added
in C99 or Fortran 95. Mr. van Rossum  appears to value backwards
compatibility less than the C or Fortran standards committees do,
although I am sure he is introducing incompatibilities only after
serious consideration. If the C or Fortran committees tried to change
the meaning of int/int, they would be shot.

If you want to be confident that your code will run, unchanged, 10
years from now on the hardware and OS that will then be common, Python
2.x is not the language to use, unfortunately. From what I have read,
Python 3 will break things more fundamental than int/int.




More information about the Python-list mailing list