If you’ve done any programming or scripting in the past, some of the object types in Table 4-1 will probably seem familiar. Even if you haven’t, numbers are fairly straightforward. Python’s core object set includes the usual suspects: integers (numbers without a fractional part), floating-point numbers (roughly, numbers with a decimal point in them), and more exotic types (unlimited-precision “long” integers, complex numbers with imaginary parts, fixed-precision decimals, and sets).
Although it offers some fancier options, Python’s basic number types are, well, basic. Numbers in Python support the normal mathematical operations. For instance, the plus sign (+) performs addition, a star (*) is used for multiplication, and two stars (**) are used for exponentiation:
>>> 123 + 222 # Integer addition 345 >>> 1.5 * 4 # Floating-pointmultiplication 6.0 >>> 2 ** 100 # 2 to the power 100 1267650600228229401496703205376L
Notice the L at the end of the last operation’s result here: Python automatically converts up to a long integer type when extra precision is needed. You can, for instance, compute 2 to the 1,000,000 power in Python (but you probably shouldn’t try to print the result—with more than 300,000 digits, you may be waiting awhile!). Watch what happens when some floating-point numbers are printed:
The first result isn’t a bug; it’s a display issue. It turns out that there are two ways to print every object: with full precision (as in the first result shown here), and in a user-friendly form (as in the second). Formally, the first form is known as an object’s as-code repr, and the second is its user-friendlystr. The difference can matter when we step up to using classes; for now, if something looks odd, try showing it with aprint statement.
Besides expressions, there are a handful of useful numeric modules that ship with Python:
>>> import math >>> math.pi 3.1415926535897931 >>> math.sqrt(85) 9.2195444572928871
Themathmodule contains more advanced numeric tools as functions, while therandommodule performs random number generation and random selections (here, from a Python list, introduced later in this chapter):
Python also includes more exotic number objects—such as complex numbers, fixed-precision decimal numbers, and sets—and the third-party open source extension domain has even more (e.g., matrixes and vectors). We’ll defer discussion of the details of these types until later in the book.
So far, we’ve been using Python much like a simple calculator; to do better justice to its built-in types, let’s move on to explore strings.
Please check back next week for the continuation of this article.