next up previous contents
Next: Lists, Tuples and Dictionaries Up: Numeric Data Previous: Functions for Numeric Data   Contents

Conversion of Scalar Types

In general, python will not automatically convert objects from one type to another, but instead provides functions to allow these conversions to be performed. One area which requires particular caution is integer arithmetic. When python evaluates arithmetic expressions which contain only integers, it performs its operations using integer arithmetic. For addition subtraction, and multiplication, this will not result in any surprises, but for division python truncates its results to the nearest integer smaller than the answer. If at least one of the numbers involved in the expression containing the division is a floating point number, then the integers involved in the computation will be temporarily converted to floating point numbers for the purpose of the computation only. The following example illustrates some of these points, as well as introducing the float conversion function.
>>> x = 3
>>> y = 2
>>> x / y
>>> float(x) / y
>>> float(x/y)
Since the values of the variables x and y were entered as integers, any arithmetic operations involving them will be carried out using integer arithmetic; thus, when 3 is divided by 2, the (integer) answer is 1. By converting either operand to a float, the expected result of 1.5 can be obtained. Other numeric conversion routines include long and int.

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
>>> 3 / 2.
>>> 3. / 2.

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, int or long) to fix the error:
>>> float('3') / 2.
This 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 failed
Since the answer isn't clear, python raises the exception. There are two possibilities: treat a as a string, and concatenate it with b, or treat b as a number and add it to a. The builtin function str can be used to temporarily convert a number to its string representation; any of the conversion functions mentioned in the previous paragraphs can be used to convert a string to a number.
>>> str(a) + b
>>> a + int(b)
Python will always be able to convert numbers to strings, but it will raise a ValueError exception if you attempt to convert a string to a number when that string does not represent a number.
next up previous contents
Next: Lists, Tuples and Dictionaries Up: Numeric Data Previous: Functions for Numeric Data   Contents
Phil Spector 2003-11-12