Difference between / vs. // operator in Python
Last Updated :
16 Oct, 2023
In this article, we will see the difference between the / vs // operator in Python
Python Division Operator
The division operator ‘/ ‘ performs standard division, which can result in a floating-point number. However, if both the dividend and divisor are integers, Python will perform integer division only if the result is an integer. Otherwise, it will produce a floating-point result.
Example
In the above example, we are performing division between two integers, 10 and 3. The result of dividing 10 by 3 is 3.3333333333333335
Python3
result = 10 / 3
print (result)
|
Output:
3.3333333333333335
Floor Division in Python
The floor division operator // performs division and returns the largest integer that is less than or equal to the division result. It truncates (rounds down) the fractional part of the result, ensuring that the result is always an integer.
Example
In result1 we are performing floor division between two integers, 10 and 3. The result of dividing 10 by 3 is 3.333…., but floor division returns the largest integer less than or equal to the result. Therefore, the result is 3.
Python3
result1 = 10 / / 3
print ( "Floor division of two integers :" , result1)
|
Output
Floor division of two integers : 3
Difference between ‘/’ and ‘//’ in Python Division
The below table shows the differences with proper examples
Floating-point. Returns in integer only if the result is an integer
|
Integer
|
Returns the fractional part
|
Truncates the fractional part
|
- 10 / 3 = 3.333333…
- 10 / 5 = 2.0
- 5 / 2 = 2.5
- -17 / 5 = -3.4
- -17 / -5 = 3.4
|
- 10 // 3 = 3
- 10 // 5 = 2
- 5 // 2 = 2
- -17 // 5 = -4
- -17 // -5 = 3
|
Please Login to comment...