Python - Float Division supporting either Python 2.X or 3.X

Introduction

/ behavior differs in 2.X and 3.X.

If your programs depend on truncating integer division, use // in both 2.X and 3.X.

If your programs require floating-point results with remainders for integers, use float to guarantee that one operand is a float around a / when run in 2.X:

X = Y // Z        # Always truncates, always an int result for ints in 2.X and 3.X 
X = Y / float(Z)  # Guarantees float division with remainder in either 2.X or 3.X 

Or you can enable 3.X / division in 2.X with a __future__ import, rather than forcing it with float conversions:

C:\Python27\python 
>>> from __future__ import division         # Enable 3.X "/" behavior 
>>> 10 / 4 
2.5 
>>> 10 // 4                                 # Integer // is the same in both 
2 

It must appear as the first executable line when used in a script file.

Related Topic