64

I came across this sample of code from a radix sort:

def getDigit(num, base, digit_num):
    # pulls the selected digit
    return (num // base ** digit_num) % base

What does the // do in Python?

sshashank124
  • 29,826
  • 8
  • 62
  • 75
Biff
  • 989
  • 3
  • 10
  • 19
  • Possible duplicate of [What does the "variable //= a value" syntax mean in Python?](http://stackoverflow.com/questions/40274205/what-does-the-variable-a-value-syntax-mean-in-python) – smci Oct 27 '16 at 10:19

3 Answers3

76

// is the floor division operator. It produces the floor of the quotient of its operands, without floating-point rounding for integer operands. This is also sometimes referred to as integer division, even though you can use it with floats, because dividing integers with / used to do this by default.

In Python 3, the ordinary / division operator returns floating point values even if both operands are integers, so a different operator is needed for floor division. This is different from Python 2 where / performed floor division if both operands were integers and floating point division if at least one of the operands was a floating point value.

The // operator was first introduced for forward-compatibility in Python 2.2 when it was decided that Python 3 should have this new ability. Together with the ability to enable the Python 3 behavior via from __future__ import division (also introduced in Python 2.2), this enables you to write Python 3-compatible code in Python 2.

user2357112
  • 235,058
  • 25
  • 372
  • 444
sepp2k
  • 353,842
  • 52
  • 662
  • 667
  • 1
    To add to the comment by @DSM -- `//` means integer division in python2.x as well. If you want to be doing integer division, you should be using `//` instead of `/` regardless of what version on python you're using. – mgilson Jan 21 '13 at 18:05
  • 2
    It rounds towards minus infinity (i.e. floor of the ratio). For negative numbers, it's different from integer division in C, which rounds towards zero. http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html – Steve Byrnes Jan 21 '13 at 18:21
8

You can just try it:

In []: 5/2
Out[]: 2

In []: 5.0/2
Out[]: 2.5

In []: 5.0//2
Out[]: 2.0

This should be self-explanatory.

(This is in Python 2.7.)

LWZ
  • 10,440
  • 19
  • 59
  • 79
  • 17
    -1: One way to figure something out is by trial and error. Another is by asking. – DilithiumMatrix Oct 25 '14 at 17:15
  • 2
    One way to answer a question is by giving a direct answer, another is by pointing direction. I did both BTW. – LWZ Oct 27 '14 at 17:13
  • 3
    I'm just trying to give you an explanation for the downvote and some feedback man. Based on the -1 for your answer, vs. +13 for the accepted... I think lots of people agree that you actually did neither. (direct or direction). – DilithiumMatrix Oct 27 '14 at 18:03
-1

Python3 supports two types of division, floating point (/) and integer (//).

Floating point: 45/2 = 22.5

Integer: 45//2 = 22