views:

222

answers:

3

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?

Thanks all!

+13  A: 

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.

Mark Rushakoff
I actually like this style better... I can remember in atleast one language I've used (VB?) the differentiating factor was `/` vs `\ ` ... but I could never remember which was which!
Matthew Scharley
The PEP also addresses the fact that backslash is reserved for escape characters or escaping newlines, so that kind of immediately eliminated `\ ` as an operator.
Mark Rushakoff
+10  A: 

// is unconditionally "truncating division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still truncates -- so you always know securely what it's gonna do.

Single / may or may not truncate depending on Python release, future imports, and even flags on which Python's run, e.g....:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may truncate, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want truncation, always use //, which guarantees it. If and when you know you don't want truncation, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

Alex Martelli
+3  A: 

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions then return floats, but those with //. This works with all versions from 2.2.0a2 on.

EOL