Zeeshan Quireshi wrote:
On Mar 3, 6:45 pm, Wells <thewellsoli...@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
float + int gives float

Similarly for '-' and '*'.

Division causes a problem because what is int / int? Should it behave
like the others and give an int? That would mean that 1 / 2 == 0, which
can be confusing for newbies.

In older languages (Fortran, for example) integer divided by integer
using the normal division operator '/' was integer, and this is what C
and those influenced by it do.

Newer languages return a float instead of an integer because it causes
less confusion (1 / 2 == 0.5 is less confusing than 1 / 2 == 0), but
also provide a special integer division operator.

In Python v2.x '/' does integer division, but from Python v3.x '/' does
float division and uses '//' for integer division. ('//' is also
available in later versions of 2.x.)
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to