When I started to learn Python 3, I used to be confused about the semantics of dividing two integers. Is the result a float or an integer value?
The reason for my confusion was a nasty Java bug that I once found in my code. The code was supposed to perform a simple division of two integers to return a parameter value between zero and one. But Java uses integer division, i.e., it skips the remainder. Thus, the value was always either zero or one, but nothing in-between. It took me days to figure that out.
Save yourself the debugging time by memorizing the following rule once and for all.
The double-backslash //
operator performs integer division and the single-backslash /
operator performs float division. An example for integer division is 40//11 = 3
. An example for float division is 40/11 = 3.6363636363636362
.
>>> # Python 3 >>> 40//11 3 >>> 40/11 3.6363636363636362
How Does Integer Division Work In Python?
Integer division consists of two steps:
- Perform normal float division
a / b.
- Round the resulting float number down to the next integer.
Here’s an example:
x = 30 // 11 print(x) # 2
Integer Division Python 2 vs 3
Python 2.x divides two integers using integer division, also known as floor division because it applies the floor function after the regular division to βround it downβ, so it evaluates the expression 5/2
to 2
. In Python 3, integer division is performed using the double frontslash 5//2
which evaluates to 2
. The single frontslash for floor division β/β is depreciated in Python 2.2+ and Python 3.
Here’s the code for integer division in Python 2 using the single frontslash operator /
:
# Python 2 print(10/3) # 3
And here’s the code for integer division in Python 3 using the double backslash operator //
:
# Python 3 print(10//3) # 3
Interactive Shell + Puzzle
You can try it in our interactive Python shell:
Exercise: What is the output of this code snippet?
Although the puzzle seems simple, more than twenty percent of the Finxter users cannot solve it. You can check whether you solved it correctly here: Test your skills now!
Arithmetic Operators
Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Calculating the sum of the two operands | 3 + 4 == 7 |
– | Subtraction | Subtracting the second operand from the first operand | 4 - 3 == 1 |
* | Multiplication | Multiplying the first with the second operand | 3 * 4 == 12 |
/ | Division | Dividing the first by the second operand | 3 / 4 == 0.75 |
% | Modulo | Calculating the remainder when dividing the first by the second operand | 7 % 4 == 3 |
// | Integer Division, Floor Division | Dividing the first operand by the second operand and rounding the result down to the next integer | 8 // 3 == 2 |
** | Exponent | Raising the first operand to the power of the second operand | 2 ** 3 == 8 |