Arithmetic operators: multiplication
An * (asterisk) sign is a multiplication operator.
Run the code below and check if our integer vs. float rule is still working.
print(2 * 3)
print(2 * 3.)
print(2. * 3)
print(2. * 3.)
Arithmetic operators: division
A / (slash) sign is a divisional operator.
The value in front of the slash is a dividend, the value behind the slash, a divisor.
Run the code below and analyze the results.
print(6 / 3)
print(6 / 3.)
print(6. / 3)
print(6. / 3.)
You should see that there is an exception to the rule.
The result produced by the division operator is always a float, regardless of whether or not the result seems to be a float at first glance: 1 / 2 , or if it looks like a pure integer: 2 / 1.
Is this a problem? Yes, it is. It happens sometimes that you really need a division that provides an integer value, not a float.
Fortunately, Python can help you with that.
Arithmetic operators: integer division
A // (double slash) sign is an integer divisional operator. It differs from the standard / operator in two details.
Run the example below and see the results:
print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)
As you can see, integer by integer division gives an integer result. All other cases produce floats.
Let's do some more advanced tests.
Look at the following snippet:
print(6 // 4)
print(6. // 4)
Imagine that we used / instead of // - could you predict the results?
Yes, it would be 1.5 in both cases. That's clear.
But what results should we expect with the // division?
Run the code and see for yourself.
What we get is two ones - one integer and one float.
The result of integer division is always rounded to the nearest integer value that is less than the real (not rounded) result.
This is very important: rounding always goes to the lesser integer.
Look at the code below and try to predict the results once again:
print(-6 // 4)
print(6. // -4)
Note: some of the values are negative. This will obviously affect the result. But how?
The result is two negative twos. The real (not rounded) result is -1.5 in both cases. However, the results are the subjects of rounding. The rounding goes toward the lesser integer value, and the lesser integer value is -2, hence -2 and -2.0.
NOTE
Integer division can also be called floor division. You will definitely come across this term in the future.