What is the reason for having '//' in Python?

Pete picture Pete · Oct 8, 2009 · Viewed 291k times · Source

I saw this in someone's code:

y = img_index // num_images

where img_index is a running index and num_images is 3.

When I mess around with // in IPython, it seems to act just like a division sign (i.e. one forward slash). I was just wondering if there is any reason for having double forward slashes?

Answer

Mark Rushakoff picture Mark Rushakoff · Oct 8, 2009

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e. quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3
3
>>> # to get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335

In Python 3:

>>> 10/3
3.3333333333333335
>>> 10//3
3

For further reference, see PEP238.