Python Division

Filed Under: Python

Python Division

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


$ python2.7
Python 2.7.10 (default, Aug 17 2018, 19:45:58) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/2
4
>>> -9/2
-5
>>> 9.0/2
4.5
>>> -9.0/2
-4.5
>>> 9//2
4
>>> -9//2
-5
>>> 9.0//2
4.0
>>> -9.0//2
-5.0
>>> 

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

Python 3 Division Operators


$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/2
4.5
>>> -9/2
-4.5
>>> 9.0/2
4.5
>>> -9.0/2
-4.5
>>> 9//2
4
>>> -9//2
-5
>>> 9.0//2
4.0
>>> -9.0//2
-5.0
>>> 

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages