Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

2.6 Numbers

Python supports five basic numerical types, three of which are integer types.

  • int (signed integers)
    • long (long integers)
    • bool (Boolean values)
  • float (floating point real numbers)
  • complex (complex numbers)

Here are some examples:

int      0101     84   -237     0x80 017 -680 -0X92
long     29979062458L  -84140l  0xDECADEDEADBEEFBADFEEDDEAL
bool     True          False
float    3.14159       4.2E-10      -90. 6.022e23          -1.609E-19
complex  6.23+1.5j     -1.23-875J   0+1j 9.80665-8.31441J  -.0224+0j

Numeric types of interest are the Python long and complex types. Python long integers should not be confused with C longs. Python longs have a capacity that surpasses any C long. You are limited only by the amount of (virtual) memory in your system as far as range is concerned. If you are familiar with Java, a Python long is similar to numbers of the BigInteger class type.

Moving forward, ints and longs are in the process of becoming unified into a single integer type. Beginning in version 2.3, overflow errors are no longer reported—the result is automagically converted to a long. In a future version of Python, the distinction will be seamless because the trailing “L” will no longer be used or required.

Boolean values are a special case of integer. Although represented by the constants True and False, if put in a numeric context such as addition with other numbers, True is treated as the integer with value 1, and False has a value of 0.

Complex numbers (numbers that involve the square root of -1, so-called “imaginary” numbers) are not supported in many languages and perhaps are implemented only as classes in others.

There is also a sixth numeric type, decimal, for decimal floating numbers, but it is not a built-in type. You must import the decimal module to use these types of numbers. They were added to Python (version 2.4) because of a need for more accuracy. For example, the number 1.1 cannot be accurately representing with binary floating point numbers (floats) because it has a repeating fraction in binary. Because of this, numbers like 1.1 look like this as a float:

>>> 1.1
1.1000000000000001
  >>> print decimal.Decimal('1.1')
  1.1

All numeric types are covered in Chapter 5.

  • + Share This
  • 🔖 Save To Your Account