Python division is done with /
, the division operator.
>>> 5/2
2.5
Python 3 does floating point division for both integer and float arguments. That’s a change from Python 2 where it would behave differently based on the type of arguments:
Python 2.7.17 (default, Nov 7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 5/2
2
>>> 5.0/2
2.5
As you can see, in Python 2.7 when dividing integers it would floor the value to produce an integer.
To do floor division in Python 3, use the //
operator:
>>> 5//2
2
>>> -5//2
-3
You can also do modulo operations using the %
operator.
One other thing to note, dividing by zero will throw a ZeroDivisionError
>>> 8 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero