Printing fractions with Python


I recently converted from bc to Python for basic calculations, and I like the fact that I can do basic arithmetic from the Python interpreter:

$ python

>>> 5.0 / 3.0
1.6666666666666667

One thing that bugged me about this was the fact that I had to add a decimal point to the input values to get a fraction as a result. While reading through one of my Python books, I came across the future module’s division feature:

$ python

>>> 5 / 3
1
>>> from __future__ import division
>>> 5 / 3
1.6666666666666667

This allow fractional values to be displayed by default, which is exactly what I’m looking for. I have been spending a bunch of time learning Ruby and Python, and so far I am really digging these languages.

This article was posted by Matty on 2009-05-04 11:29:00 -0400 -0400