What is the double slash operator and what does the double slash operator
// do in Python?
The double slash operator in Python returns the quotient value from a division operation. The operator requires two numbers: a dividend and a divisor, which are the same numbers used with standard division operations in mathematics.
For example, the mathematical expression
75 ÷ 10 has the 75 as the dividend, 10 as the divisor and returns the value 7 as quotient and 5 remainder. Therefore, when the double slash operator is used in Python on the same mathematical calculation the result will be just 7, as seen in the Python REPL below:
>>> 75 // 10 7
While this operator can be handy in performing the same basic mathematical calculations used in school by providing the quotient value exclusive of any remainders, it can also help in rounding up or down numbers without using any import declarations.
Round Down Or Truncate Number Without Importing
How can you round down a number without importing any libraries in Python?
If you have a positive number and wanted to truncate this number by removing any decimal portion from it you could simply apply the double slash operator with 1 as the divisor.
For example, here’s a demonstration of rounding down some positive numbers:
>>> 12.34567 // 1 12.0 >>> 12.00000001 // 1 12.0
Notice these numbers are positive, this doesn’t work when used on negative numbers, as demonstrated below:
>>> -3.1 // 1 -4.0
As you can see from the above code when handling negative numbers it’s not doing so in the same way when handling positive numbers.
To round down negative numbers in Python you will need to swap the divisor for -1 and wrap with a negative sign to retain the number as negative, as seen below:
>>> -(-3.1 // -1) -3.0
Unfortunately handling negative numbers isn’t as elegant and simple as handling positive numbers, but the same approach can be used when rounding up positive numbers.
How To Round Up Numbers Without
In the same way the double slash operator is used for negative numbers to truncate (round down) their number, the same approach can be used to round up positive numbers.
Here’s an example demonstrating rounding up:
>>> -(12.0000001 // -1) 13.0
Conversely, when rounding up negative numbers, instead of having -1 as the divisor it’s like the rounding down of the positive number:
>>> -3.1 // 1 -4.0
As you can see the double slash operator provides the quotient value from a division operation in Python. It could also be used as an alternative rounding up or down (truncation) of numbers too.
The double slash operator is a simple way of being able to get the quotient number from a division operation.
It can also be used as a way to round up or truncate a number by providing its whole integer number rather than the decimal portion.