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.








Fazal Majid on May 4th, 2009
Python is great!. The behavior you want (real division vs. integer division) will be the default in future versions of Python (you will have to use 3 // 2) to get the Euclidian division. The “from __future__” mumbo-jumbo is just a way to ease the transition for planned changes to the language, by letting developers test for them without requiring old code to be revised immediately.
If you want to make this the default for your interactive Python interpreter sessions, set your PYTHONSTARTUP environment variable to the name of a file that makes that transition statement, .e.g $HOME/.pythonrc.py