Conversion of Scalar Types

>>> x = 3 >>> y = 2 >>> x / y 1 >>> float(x) / y 1.5 >>> float(x/y) 1.0Since the values of the variables

When values in a computation are numbers rather than variable names, it suffices to include a decimal point in any of the operands of an arithmetic expression to insure that the entire computation will be carried out using floating point arithmetic, but there is no harm in including decimal points (or exponential notation) for all the operands. Thus the following expressions all result in the same answer:

>>> 3. / 2 1.5 >>> 3 / 2. 1.5 >>> 3. / 2. 1.5

These conversion routines are also necessary to convert numbers represented as
strings into actual python numeric values. If you attempt to use a string value,
even if it is a representaion of a number, as a numeric value, it will raise
a `TypeError`:

>>> '3' / 2. Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: bad operand type(s) for /Simply pass the string to the appropriate conversion function (

>>> float('3') / 2. 1.5This same technique is required when numbers are read from a file, since in this case they will enter the python environment as strings.

If you have two numeric values and simply want to convert them to a common
type, the function `coerce` can be used. If you consider the hierarchy of
integer, long integer, floating point number and complex number, `coerce`
converts the argument which is lower in the hierarchy to the type of the argument
which is higher. The following examples illustrate this point:

>>> coerce(3,5L) (3L, 5L) >>> coerce(3,5.) (3.0, 5.0) >>> coerce(3L,5.) (3.0, 5.0) >>> coerce(3.,2.+1j) ((3+0j), (2+1j))

One other area where explicit conversion is needed is when trying to operate on
numbers and strings together. Since python relies on operator overloading to
perform many common tasks, it will generate a `TypeError` when you ask it
to perform such operations on dissimilar types. For example, consider the variable
`a`, with a numeric value of 7, and the variable 'b' with the string value
of ```8`''. What should python do when you ask to ``add'' together these
two values?

>>> a = 7 >>> b = '8' >>> a + b Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: number coercion failedSince the answer isn't clear, python raises the exception. There are two possibilities: treat

>>> str(a) + b '78' >>> a + int(b) 15Python will always be able to convert numbers to strings, but it will raise a