Python 2 versus Python 3 division


 

In Python 2, the division operator ("/") behaves differently than it does in Python 3. In Python 2, the division operator performs "floor division" when both operands are integers. Floor division rounds the result down to the nearest whole number, discarding any remainder. For example, the expression "5 / 2" evaluates to 2 in Python 2.

In Python 3, the division operator always performs "true division", which returns a decimal value regardless of the types of the operands. For example, the expression "5 / 2" evaluates to 2.5 in Python 3.

To perform floor division in Python 3, you can use the "//" operator. For example, the expression "5 // 2" evaluates to 2 in Python 3.

# Python 2 >>> 5 / 2 2 # Python 3 >>> 5 / 2 2.5 >>> 5 // 2 2

It is important to note that when we upgrade our code from python 2 to python 3, we have to keep in mind the difference in the division operator as it can change the outcome of the code. For example, if we are working with a code which performs a lot of mathematical operation, the change in the division operator can cause the code to behave differently.

It is also worth mentioning that python 2 has a different behavior for the division operator when working with negative integers. In python 2, for example, the expression "-5 / 2" will evaluate to -2, while in python 3 the expression "-5 // 2" will evaluate to -3.

In conclusion, when working with python 2 code, it is important to be aware of the difference in the division operator and how it affects the outcome of mathematical operations. When upgrading to python 3, it is also important to keep this difference in mind in order to ensure that the code behaves as expected.


No comments

Powered by Blogger.