Python Division with Examples

 

Python supports two division operators: / and //. But Why?

Actually, there is a history behind it. There was only one division operator (/) in the initial releases of Python. However, its working was ambiguous. For integers, it used to return integer value by floor division whereas, for floats, it was returning float values. There was no true-division operator in Python.

In order to fix this – Python 2.2 introduced a new floor-division operator (//) and allowed developers to migrate their applications to use it wherever they wanted floor integer division. This change was performed under PEP-238. Finally, in Python 3, the division operator (/) started working as a true-division operator.

Let’s look into some simple code snippets to understand Python division operators.

Python 2 Division Operators

Note that if you are on Python 2.1 or lesser version then // will not work.

Python 3 Division Operators

Below table shows the output and explanation for better understanding.

Division Expression Python 2 Python 3 Explanation
9/2 4 4.5 For integers, Python 2 always returns int and returns floor value. Whereas Python 3 returns float value
-9/2 -5 -4.5 Since Python 2 returns floor value, it’s returning -5.
9.0/2 4.5 4.5 With floats, both Python 2 and Python 3 returns float and their behavior is same.
-9.0/2 -4.5 -4.5 Same as above.
9//2 4 4 Floor division operator, works same way in both Python 2 and Python 3.
-9//2 -5 -5
9.0//2 4.0 4.0
-9.0//2 -5.0 -5.0

Conclusion

If you are on Python 2 and planning to migrate to Python 3 then please look at the way your division operators are being used. If needed, change them to use floor division operator or else leave them to work as a true division operator.

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: