5.6. Built-in Functions

5.6.1. Standard Type Functions

In 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 int'>
>>> type(2-1j)
<type 'complex'>

5.6.2. Numeric Type Functions

Python 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

The int(), long(), float(), and complex() built-in 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.

The following are some examples using the numeric type conversion built-ins:

>>> 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.4 nutshells these numeric type conversion built-in functions.

Table 5.4. Numeric Type Conversion Built-in Functions
function operation
int( obj, base=10 ) converts string or number obj to (plain) integer; provides same behavior as string.atoi(); optional base argument introduced in 1.6
long( obj, base=10 ) converts string or number obj to long integer; provides same behavior as string.atol(); optional base argument introduced in 1.6
float( obj ) converts string or number obj to floating point; provides same behavior as string.atof()
complex( str ) or complex( real, imag =0.0) converts string str to complex, or takes real (and perhaps imag inary) numbers and returns a complex number with those components

Operational

Python 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 standalone 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
>>>
>>> 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 third 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:

  • int() chops off the decimal point and everything after (a.k.a. truncation).

  • floor() rounds you to the next smaller integer, i.e., the next integer moving in a negative direction (towards the left on the number line).

  • round() (rounded zero digits) rounds you to the nearest integer period.

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)	%+.1f" % (eachNum, float(int(eachNum)))
…     print "floor(%.1f)	%+.1f" % (eachNum,
…     math.floor(eachNum))
…     print "round(%.1f)	%+.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

Table5.5 summarizes the operational functions for numeric types:

Table 5.5. Numeric Type Operational Built-in Functions[a]
function operation
abs( num ) returns the absolute value of num
coerce( num1, num2 ) converts num1 and num2 to the same numeric type and returns the converted pair as a tuple
divmod( num1, num2 ) division-modulo combination returns (num1 / num2, num1 % num2) as a tuple. For floats and complex, the quotient is rounded down (complex uses only real component of quotient)
pow( num1, num2, mod =1) raises num1 to num2 power, quantity modulo mod if provided
round( flt, ndig =0) (floats only) takes a float flt and rounds it to ndig digits, defaulting to zero if not provided

[a] except for round(), which applies only to floats

5.6.3. Integer-only Functions

In 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 Representation

As 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 which 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 Conversion

Python 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.6 shows all built-in functions for integer types.

Table 5.6. Integer Type Built-in Functions
function operation
hex( num ) converts num to hexadecimal and return as string
oct( num ) converts num to octal and return as string
chr( num ) takes ASCII value num and returns ASCII character as string; 0 <= num <= 255 only
ord( chr ) takes ASCII chr and returns corresponding ordinal ASCII value; chr must be a string of length 1

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset