Python - Classic, Floor, and True Division


Division behaves slightly differently in Python 3.X and 2.X.

There are actually three flavors of division, and two different division operators, one of which changes in 3.X.

This is another major change in 3.X and can break 2.X code

X / Y

Classic and true division.

In Python 2.X, this operator performs classic division, truncating results for integers, and keeping remainders (fractional parts) for floating-point numbers.

In Python 3.X, it performs true division, always keeping remainders in floating-point results, regardless of types.

X // Y

Floor division.

Added in Python 2.2 and available in both Python 2.X and 3.X.

This operator truncates fractional remainders down to their floor, regardless of types.

Its result type depends on the types of its operands.

True division

True division addresses that the results of the original classic division model are dependent on operand types.

It can be difficult to anticipate in a dynamically typed language like Python.

Classic division was removed in 3.X because of this constraint.

The / and // operators implement true and floor division in 3.X.

Python 2.X defaults to classic and floor division, but you can enable true division as an option.


In 3.X, the / performs true division, returning a float result that includes any remainder, regardless of operand types.

The // performs floor division, which truncates the remainder and returns an integer for integer operands or a float if any operand is a float.

In 2.X, the / does classic division, performing truncating integer division if both operands are integers and float division (keeping remainders) otherwise.

The // does floor division and works as it does in 3.X, performing truncating division for integers and floor division for floats.


>>> 10 / 4            # Differs in 3.X: keeps remainder 
>>> 10 / 4.0          # Same in 3.X: keeps remainder 
>>> 10 // 4           # Same in 3.X: truncates remainder 
>>> 10 // 4.0         # Same in 3.X: truncates to floor 

>>> 10 / 4            # This might break on porting to 3.X! 
>>> 10 / 4.0 
>>> 10 // 4           # Use this in 2.X if truncation needed 
>>> 10 // 4.0 

Here, the data type of the result for // is still dependent on the operand types in 3.X: if either is a float, the result is a float; otherwise, it is an integer.

Using // instead of / in 2.X when integer truncation is required helps make code 3.X-compatible.

Related Topic