Question about typing: ints/floats

Mensanator mensanator at aol.com
Wed Mar 3 19:27:50 EST 2010


On Mar 3, 5:45 pm, Wells <thewellsoli... 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.
> 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.

Not in Python 3.1:
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = 1
>>> b = 3
>>> a/b
0.3333333333333333



> Changing 'b' to 3.0 will yield a
> float as a result (0.33333333333333331)
>
> Is there some way to explain the consistency here?

Yes, use Python 3.1.

> Does python
> implicitly change the casting when you add variables of a different
> numeric type?

Sometimes. Floats and ints are compatible. But this doesn't work:

>>> '3' + 1
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    '3' + 1
TypeError: Can't convert 'int' object to str implicitly


>
> Anyway, just  curiosity more than anything else. Thanks!




More information about the Python-list mailing list