Question about typing: ints/floats

Albert van der Horst albert at spenarnc.xs4all.nl
Sat Mar 13 15:53:35 CET 2010


In article <mailman.266.1267666113.23598.python-list at python.org>,
MRAB  <python at mrabarnett.plus.com> wrote:
>Zeeshan Quireshi wrote:
>> On Mar 3, 6: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. 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, like most other languages performs only integer division when
>> both the operands are ints. So only if one of the types is a flot or
>> you explicitly cast your expression to be a double, then the value
>> will be a fraction. otherwise you will the quotient.
>
>int + int gives int
>float + float gives float
>int + float gives float

You skip a step here that the OP may have missed.
a = 1
a += 1.222
This invokes the calculation
    1 + 1.222
which is int + float.

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list