Python Programming/Numbers

From Wikibooks, open books for an open world
Jump to: navigation, search

Python supports 4 types of Numbers, the int, the long, the float and the complex. You don’t have to specify what type of variable you want; Python does that automatically.

  • Int: This is the basic integer type in python, it is equivalent to the hardware 'c long' for the platform you are using.
  • Long: This is a integer number that's length is non-limited. In python 2.2 and later, Ints are automatically turned into long ints when they overflow.
  • Float: This is a binary floating point number. Longs and Ints are automatically converted to floats when a float is used in an expression, and with the true-division // operator.
  • Complex: This is a complex number consisting of two floats. Complex literals are written as a + bj where a and b are floating-point numbers denoting the real and imaginary parts respectively.

In general, the number types are automatically 'up cast' in this order:

Int → Long → Float → Complex. The farther to the right you go, the higher the precedence.

>>> x = 5
>>> type(x)
<type 'int'>
>>> x = 187687654564658970978909869576453
>>> type(x)
<type 'long'>
>>> x = 1.34763
>>> type(x)
<type 'float'>
>>> x = 5 + 2j
>>> type(x)
<type 'complex'>

However, some expressions may be confusing since in the current version of python, using the / operator on two integers will return another integer, using floor division. For example, 5/2 will give you 2. You have to specify one of the operands as a float to get true division, e.g. 5/2. or 5./2 (the dot specifies you want to work with float) to have 2.5. This behavior is deprecated and will disappear in a future python release as shown from the from __future__ import.

>>> 5/2
2
>>>5/2.
2.5
>>>5./2
2.5
>>> from __future__ import division
>>> 5/2
2.5
>>> 5//2
2