Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Integer division and the future

  • future
from __future__ import print_function

print(3/2)
$ python divide.py
1

$ python3 divide.py
1.5
from __future__ import print_function
from __future__ import division

print(3/2)     # 1.5

If you need to use Python 2, remember that by default division is integer based so 3/2 would return 1. Importing the 'division' directive from future changes this to the behavior that we usually expect 3/2 being 1.5. This is also the behavior we have in Python 3. In case you already use Python 3 and would like to get the "old" behavior, that is to get the integer part of the division, you can always call the "int" function: int(b/a).