Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
Is this intended? I strongly remember earlier versions returning int/int=int
? What should I do, is there a new division operator or must I always cast?
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like
+
,-
,*
and/
to special functions, such that e.g.a + b
is equivalent toRegarding division in Python 2, there is by default only
/
which maps to__div__
and the result is dependent on the input types (e.g.int
,float
).Python 2.2 introduced the
__future__
featuredivision
, which changed the division semantics the following way (TL;DR of PEP 238):/
maps to__truediv__
which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)//
maps to__floordiv__
, which should return the floored result of/
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method
__div__
in Python's object model.If you want to use the same code in Python 2 and Python 3 use
and stick to the PEP 238 semantics of
/
and//
.Take a look at PEP-238: Changing the Division Operator
Oops, immediately found
2//2
.Hope it might help someone instantly.
Behavior of Division Operator in Python 2.7 and Python 3
to get the result in double multiple 1.0 to "dividend or divisor"