Python // operator is also called floor division operator. It is one of the arithmetic operators in Python. It works on numbers in Python.
Python // Operator
It’s similar to a division operator except that it returns the integer part of the division operation. So, if the output of division is 3.999, this will return 3. That’s why it’s called floor division operator.
Let’s look at some examples of floor division in Python.
1. Floor division with integers
>>> 10//3 3 >>> 10//2 5
2. Floor division with floats
>>> 10.0//3 3.0 >>> 10//2.0 5.0 >>> 11.99//3.00 3.0
3. Floor division with complex numbers
Complex numbers don’t support floor division. If we try to use // operator with complex numbers, it will throw TypeError: can’t take floor of complex number.
>>> x = 10 + 3j >>> type(x) <class 'complex'> >>> x // 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't take floor of complex number. >>>
Overloading // Operator
We know that Python supports operator overloading. If you want to support the // operator for an object, you need to override __floordiv__(self, other) method. Let’s look at a simple example of overloading floor division operator.
# Floor Division Operator overloading example class Data: id = 0 def __init__(self, i): self.id = i def __floordiv__(self, other): print("overloading // operator") return self.id // other.id d1 = Data(10) d2 = Data(3) print(d1 // d2)
- Python // operator works with numbers – int and float.
- The floor division operator returns the integer part of the division operation.
- If both dividend and divisor are integers, the floor division will also return int.
- If one of the dividends and divisor is float, the floor division will return a float.
- We can’t use the // operator with complex numbers.