Question about typing: ints/floats

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Mar 4 02:13:50 CET 2010


On Wed, Mar 3, 2010 at 6: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.
> 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)
>
> Is there some way to explain the consistency here? Does python
> implicitly change the casting when you add variables of a different
> numeric type?
>
> Anyway, just  curiosity more than anything else. Thanks!
> --
>

Python doesn't cast anything. Variable names in python do not have types.
It's the objects bound to the names that have types.

a += 1.202 does not change a in place. It is exactly the same thing as
writing
a = a + 1.202

In Python (like many other languages), int + float returns a float. That
float is then assigned to the name "a".

In Python 2, all operations with two int operands return an int, including
division. This was changed in Python 3 so that 1 / 3 will return a float and
1 // 3 will do integer division.


> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100303/c48187fd/attachment.html>


More information about the Python-list mailing list