Division Operators in Python?

PythonServer Side ProgrammingProgramming

Generally, the data type of an expression depends on the types of the arguments. This rule is applied to most of the operators: like when we add two integers ,the result should be an integer. However, in case of division this doesn’t work out well because there are two different expectations. Sometimes we expect division to generate create precise floating point number and other times we want a rounded-down integer result.

In general, the python definition of division(/) depended solely on the arguments. For example in python 2.7, dividing 20/7 was 2 because both arguments where integers. However, 20./7 will generate 2.857142857142857 as output because the arguments were floating point numbers.

Above definition of ‘/’ often caused problems for applications where data types were used that the author hadn’t expected.

Consider a simple program of converting temperature from Celsius to Fahrenheit conversion will produce two different results depending on the input. If one user provide integer argument(18) and another floating point argument(18.0), then answers were totally different, even though all of the inputs had the equal numeric values.

#Conversion of celcius to Fahrendheit in python 2.6
>>> print 18*9/5 + 32
>>> print 18.0*9/5 + 32
>>> 18 == 18.0

From above we can see, when we pass the 18.0, we get the correct output and when we pass 18, we are getting incorrect output. This behaviour is because in python 2.x, the “/” operator works as a floor division in case all the arguments are integers. However, if one of the argument is float value the “/” operator returns a float value.

An explicit conversion function(like float(x)) can help prevent this. The idea however, is for python be simple and sparse language, without a dense clutter of conversions to cover the rare case of an unexpected data type. Starting with Python 2.2 version, a new division operator was added to clarify what was expectred. The ordinary / operator will, in the future, return floating-point results. A special division operator, //, will return rounded-down results.

>>> # Python 2.7 program to demonstrate the use of "//" for both integers and floating point number
>>> print 9//2
>>> print -9//2
>>> print 9.0//2
>>> print -9.0//2

Division Operation in Python 3.x

In python 3.x, above mentioned flaws were removed and the ‘/’ operator does floating point division for both integer and floating point arguments.

>>> #Conversion of celcius to Fahrendheit in python 3.x
>>> #Passing 18 (integer)
>>> print (18*9/5 + 32)
>>> #Passing 18.0(float)
>>> print(18.0*9/5 + 32)

Also there is no difference when we pass +ve or –ve arguments.

>>> print(9/2)
>>> print(-9/2)
>>> print(9.0/2)
>>> print(-9.0/2)
Published on 02-May-2019 11:29:32