Two forward slashes in Python

PythonFloor Division

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

// 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.

Solution 2 - Python

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.)

Solution 3 - Python

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

Floating point: 45/2 = 22.5

Integer: 45//2 = 22

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBiffView Question on Stackoverflow
Solution 1 - Pythonsepp2kView Answer on Stackoverflow
Solution 2 - PythonLWZView Answer on Stackoverflow
Solution 3 - PythonJason SawickiView Answer on Stackoverflow