1/2 evaluates to 0

Peter Otten __peter__ at web.de
Wed Oct 12 06:34:58 EDT 2011


Laurent Claessens wrote:

> This is well known :
> 
>  >>> 1/2
> 0
> 
> This is because the division is an "integer division".
> 
> My question is : how can I evaluate 1/2 to 0.5 ? Is there some non
> integer division operator ?
> Up to now I workarounded writing float(1)/2. Is there an other way ?
> 
> My Zen of python says :
> There should be one-- and preferably only one --obvious way to do it.
> 
> and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch)

In Python 3 there is an obvious way:

>>> 1/2
0.5

In Python 2 you can trigger that behaviour with the magic incantation

>>> from __future__ import division
>>> 1/2
0.5

In both cases the traditional integer division can be forced with

>>> 1//2
0





More information about the Python-list mailing list