Question about typing: ints/floats

Chris Rebert clp2 at rebertia.com
Wed Mar 3 20:06:01 EST 2010


On Wed, Mar 3, 2010 at 3:45 PM, Wells <thewellsoliver at gmail.com> wrote:
> This seems sort of odd to me:
>
>>>> a = 1
>>>> a += 1.202
>>>> a
> 2.202
>
> Indicates that 'a' was an int that was implicitly casted to a float.

Remember Python is dynamically typed. Values have types, but variables
don't (I could do a = "foo" at the end of your code and Python won't
complain).
But yes, internally, Python converted the int to a float before doing
the addition.

> But:
>
>>>> a = 1
>>>> b = 3
>>>> a / b
> 0
>
> This does not implicitly do the casting, it treats 'a' and 'b' as
> integers, and the result as well. Changing 'b' to 3.0 will yield a
> float as a result (0.33333333333333331)

This has been fixed in Python v3.x
You can request the new behavior in earlier versions using a magic import:

>>> from __future__ import division
>>> a = 1
>>> b = 3
>>> a / b
0.33333333333333331

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list