[Tutor] How can I let the Python Console display more decimal precision?

Steven D'Aprano steve at pearwood.info
Thu Jun 12 14:31:05 CEST 2014


On Thu, Jun 12, 2014 at 08:48:25AM +0800, Marino David wrote:
> Hi All:
> 
> I am a newbie at the Python.
> 
> I type "26/12" in Python Console and get result of "2".
> 
> It is obvious that the corresponding result should be 2.3333...... I don't
> know why the Console only returns the integer part of  true result. Anyone
> can help me out?

Try this instead:

26.0/12

and it will print a fractional number instead of an int:

py> 26.0/12
2.1666666666666665


What's going on?

Back in the early mists of time, when Python first came out, Python's 
creator Guido van Rossum decided that the / division operator should 
behave like in the C programming language. In C, division of two 
integers performs *integer division*, and drops the remainder, while 
division of one or more floating point number keeps the remainder as a 
fraction:

1/2 => 0
1/2.0 => 0.5

That was one of those decisions that seemed like a good idea at the 
time, but turned out to be a mistake. But for backwards compatibility, 
Python had to keep it until recently.

In Python version 3, / now does calculator division, like you expect. 
But in Python 2, you have to either convert one or both numbers to a 
float, or you can put this at the top of your program:

from __future__ import division

Note that there are TWO underscores at the beginning and end of 
"future".


If you want integer division, where the remainder is ignored, you can 
use the // operator:

py> 26.0//12
2.0



-- 
Steven


More information about the Tutor mailing list