Division

suggest change

Python does integer division when both operands are integers. The behavior of Python’s division operators have changed from Python 2.x and 3.x (see also http://stackoverflow.com/documentation/python/809/incompatibilities-moving-from-python-2-to-python-3/2797/integer-division ).

a, b, c, d, e = 3, 2, 2.0, -3, 10

In Python 2 the result of the ’ / ’ operator depends on the type of the numerator and denominator.

a / b                  # = 1 

a / c                  # = 1.5

d / b                  # = -2

b / a                  # = 0

d / e                  # = -1

Note that because both a and b are ints, the result is an int.

The result is always rounded down (floored).

Because c is a float, the result of a / c is a float.

You can also use the operator module:

import operator        # the operator module provides 2-argument arithmetic functions
operator.div(a, b)     # = 1
operator.__div__(a, b) # = 1

What if you want float division:

Recommended:

from __future__ import division # applies Python 3 style division to the entire module
a / b                  # = 1.5 
a // b                 # = 1

Okay (if you don’t want to apply to the whole module):

a / (b * 1.0)          # = 1.5
1.0 * a / b            # = 1.5
a / b * 1.0            # = 1.0    (careful with order of operations)

from operator import truediv
truediv(a, b)          # = 1.5

Not recommended (may raise TypeError, eg if argument is complex):

float(a) / b           # = 1.5
a / float(b)           # = 1.5

The ’ // ’ operator in Python 2 forces floored division regardless of type.

a // b                # = 1
a // c                # = 1.0

In Python 3 the / operator performs ‘true’ division regardless of types. The // operator performs floor division and maintains type.

a / b                  # = 1.5 
e / b                  # = 5.0
a // b                 # = 1
a // c                 # = 1.0

import operator            # the operator module provides 2-argument arithmetic functions
operator.truediv(a, b)     # = 1.5
operator.floordiv(a, b)    # = 1
operator.floordiv(a, c)    # = 1.0

Possible combinations (builtin types):

See PEP 238 for more information.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Simple Mathematical Operators:
* Division

Table Of Contents
2 Filter
3 List
7 Loops
21 Simple Mathematical Operators
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve