5.6. Built-in and Factory Functions5.6.1. Standard Type FunctionsIn the last chapter, we introduced the cmp(), str(), and type() built-in functions that apply for all standard types. For numbers, these functions will compare two numbers, convert numbers into strings, and tell you a number's type, respectively. Here are some examples of using these functions: >>> cmp(-6, 2) -1 >>> cmp(-4.333333, -2.718281828) -1 >>> cmp(0xFF, 255) 0 >>> str(0xFF) '255' >>> str(55.3e2) '5530.0' >>> type(0xFF) <type 'int'> >>> type(98765432109876543210L) <type 'long'> >>> type(2-1j) <type 'complex'> 5.6.2. Numeric Type FunctionsPython currently supports different sets of built-in functions for numeric types. Some convert from one numeric type to another while others are more operational, performing some type of calculation on their numeric arguments. Conversion Factory FunctionsThe int(), long(), float(), and complex() functions are used to convert from any numeric type to another. Starting in Python 1.5, these functions will also take strings and return the numerical value represented by the string. Beginning in 1.6, int() and long() accepted a base parameter (see below) for proper string conversionsit does not work for numeric type conversion. A fifth function, bool(), was added in Python 2.2. At that time, it was used to normalize Boolean values to their integer equivalents of one and zero for true and false values. The Boolean type was added in Python 2.3, so true and false now had constant values of TRue and False (instead of one and zero). For more information on the Boolean type, see Section 5.7.1.
In addition, because of the unification of types and classes in Python 2.2, all of these built-in functions were converted into factory functions. Factory functions, introduced in Chapter 4, just means that these objects are now classes, and when you "call" them, you are just creating an instance of that class. They will still behave in a similar way to the new Python user so it is probably something you do not have to worry about. The following are some examples of using these functions: >>> int(4.25555) 4 >>> long(42) 42L >>> float(4) 4.0 >>> complex(4) (4+0j) >>> >>> complex(2.4, -8) (2.4-8j) >>> >>> complex(2.3e-10, 45.3e4) (2.3e-10+453000j) Table 5.5 summarizes the numeric type factory functions.
OperationalPython has five operational built-in functions for numeric types: abs(), coerce(), divmod(), pow(), and round(). We will take a look at each and present some usage examples. abs() returns the absolute value of the given argument. If the argument is a complex number, then math.sqrt(num .real2 + num.imag2) is returned. Here are some examples of using the abs() built-in function: >>> abs(-1) 1 >>> abs(10.) 10.0 >>> abs(1.2-2.1j) 2.41867732449 >>> abs(0.23 - 0.78) 0.55 The coerce() function, although it technically is a numeric type conversion function, does not convert to a specific type and acts more like an operator, hence our placement of it in our operational built-ins section. In Section 5.5.1, we discussed numeric coercion and how Python performs that operation. The coerce() function is a way for the programmer to explicitly coerce a pair of numbers rather than letting the interpreter do it. This feature is particularly useful when defining operations for newly created numeric class types. coerce() just returns a tuple containing the converted pair of numbers. Here are some examples: >>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>> >>> coerce(1.23-41j, 134L) ((1.23-41j), (134+0j)) The divmod() built-in function combines division and modulus operations into a single function call that returns the pair (quotient, remainder) as a tuple. The values returned are the same as those given for the classic division and modulus operators for integer types. For floats, the quotient returned is math.floor(num1/num2) and for complex numbers, the quotient is math.floor((num1/num2).real). >>> divmod(10,3) (3, 1) >>> divmod(3,10) (0, 3) >>> divmod(10,2.5) (4.0, 0.0) >>> divmod(2.5,10) (0.0, 2.5) >>> divmod(2+1j, 0.5-1j) (0j, (2+1j)) Both pow() and the double star ( ** ) operator perform exponentiation; however, there are differences other than the fact that one is an operator and the other is a built-in function. The ** operator did not appear until Python 1.5, and the pow() built-in takes an optional third parameter, a modulus argument. If provided, pow() will perform the exponentiation first, then return the result modulo the third argument. This feature is used for cryptographic applications and has better performance than pow(x,y) % z since the latter performs the calculations in Python rather than in C-like pow(x, y, z). >>> pow(2,5) 32 >>>s >>> pow(5,2) 25 >>> pow(3.141592,2) 9.86960029446 >>> >>> pow(1+1j, 3) (-2+2j) The round() built-in function has a syntax of round(flt,ndig=0). It normally rounds a floating point number to the nearest integral number and returns that result (still) as a float. When the optional ndig option is given, round() will round the argument to the specific number of decimal places. >>> round(3) 3.0 >>> round(3.45) 3.0 >>> round(3.4999999) 3.0 >>> round(3.4999999, 1) 3.5 >>> import math >>> for eachNum in range(10): ... print round(math.pi, eachNum) ... 3.0 3.1 3.14 3.142 3.1416 3.14159 3.141593 3.1415927 3.14159265 3.141592654 3.1415926536 >>> round(-3.5) -4.0 >>> round(-3.4) -3.0 >>> round(-3.49) -3.0 >>> round(-3.49, 1) -3.5 Note that the rounding performed by round() moves away from zero on the number line, i.e., round(.5) goes to 1 and round(-.5) goes to -1. Also, with functions like int(), round(), and math.floor(), all may seem like they are doing the same thing; it is possible to get them all confused. Here is how you can differentiate among these:
Here is the output for four different values, positive and negative, and the results of running these three functions on eight different numbers. (We reconverted the result from int() back to a float so that you can visualize the results more clearly when compared to the output of the other two functions.) >>> import math >>> for eachNum in (.2, .7, 1.2, 1.7, -.2, -.7, -1.2, -1.7): ... print "int(%.1f)\t%+.1f" % (eachNum, float(int(eachNum))) ... print "floor(%.1f)\t%+.1f" % (eachNum, ... math.floor(eachNum)) ... print "round(%.1f)\t%+.1f" % (eachNum, round(eachNum)) ... print '-' * 20 ... int(0.2) +0.0 floor(0.2) +0.0 round(0.2) +0.0 -------------------- int(0.7) +0.0 floor(0.7) +0.0 round(0.7) +1.0 -------------------- int(1.2) +1.0 floor(1.2) +1.0 round(1.2) +1.0 -------------------- int(1.7) +1.0 floor(1.7) +1.0 round(1.7) +2.0 -------------------- int(-0.2) +0.0 floor(-0.2) -1.0 round(-0.2) +0.0 -------------------- int(-0.7) +0.0 floor(-0.7) -1.0 round(-0.7) -1.0 -------------------- int(-1.2) -1.0 floor(-1.2) -2.0 round(-1.2) -1.0 -------------------- int(-1.7) -1.0 floor(-1.7) -2.0 round(-1.7) -2.0 Table 5.6 summarizes the operational functions for numeric types.
5.6.3. Integer-Only FunctionsIn addition to the built-in functions for all numeric types, Python supports a few that are specific only to integers (plain and long). These functions fall into two categories, base presentation with hex() and oct(), and ASCII conversion featuring chr() and ord(). Base RepresentationAs we have seen before, Python integers automatically support octal and hexadecimal representations in addition to the decimal standard. Also, Python has two built-in functions that return string representations of an integer's octal or hexadecimal equivalent. These are the oct() and hex() built-in functions, respectively. They both take an integer (in any representation) object and return a string with the corresponding value. The following are some examples of their usage: >>> hex(255) '0xff' >>> hex(23094823l) '0x1606627L' >>> hex(65535*2) '0x1fffe' >>> >>> oct(255) '0377' >>> oct(23094823l) '0130063047L' >>> oct(65535*2) '0377776' ASCII ConversionPython also provides functions to go back and forth between ASCII (American Standard Code for Information Interchange) characters and their ordinal integer values. Each character is mapped to a unique number in a table numbered from 0 to 255. This number does not change for all computers using the ASCII table, providing consistency and expected program behavior across different systems. chr() takes a single-byte integer value and returns a one-character string with the equivalent ASCII character. ord() does the opposite, taking a single ASCII character in the form of a string of length one and returns the corresponding ASCII value as an integer: >>> ord('a') 97 >>> ord('A') 65 >>> ord('0') 48 >>> chr(97) 'a' >>> chr(65L) 'A' >>> chr(48) '0' Table 5.7 shows all built-in functions for integer types.
|