See All Titles |
![]() ![]() ExpressionsPython operators support a wide range of expressions, such as >>> x,y,z = z-x, y*z, x+y # Parallel assignment: example 1 >>> x,y,z = 5,4,3 # Parallel assignment: example 2 >>> a,b = b,a # Switching assignments >>> a = b = c = 10 # Multiple assignments >>> string.atof(s) # Functions support >>> 20 < x < 40 # Multiple range testing The last example is equivalent to >>> 20 < x and x < 40 Built-In FunctionsThe following functions are always available when you load the Python interpreter. You don't need to import them because they are already part of the __builtin__ module, which is always imported when you launch Python. apply()It executes a given function, passing the arguments provided. basic syntax: apply(function, (tuple of positional arguments) [, dictionary of keywords arguments]) >>> apply (raise_salary, (6000), {'employee':'John', 'id':13}) Note that starting at Python 1.6, the functionality of apply is now available with normal function calling, such as >>> args = (6000,) >>> kwargs = { 'employee':'John', 'id':13} >>> raise_salary(*args, **kwargs) coerce()coerce is used to try to convert the two given arguments x and y to the same type, returning them as a tuple. >>> coerce(42,5.4) (42.0, 5.4) filter()It creates a new list by taking each element of list for which function evaluates to true. basic syntax: filter( function, list ) >>> a = range (4) >>> b = filter(lambda x: x < 3, a) >>> print b [0,1,2] globals()It returns the global namespace dictionary. input()It provides an input interface for the user. Only numbers are accepted. basic syntax: input( [prompt] ) a = input("Please, type a number greater than 5: ") if a<5: print "a is not greater than 5" locals()It returns the local namespace dictionary map()It applies a function to each element of list, producing another list. If function is set to None and multiple lists are provided, a tuple matrix is generated in the format of a list. basic syntax: map( function, list ) >>> lst = map(None, [1,2,3,4], [1,2,3,4,5,6]) >>> lst [(1, 1), (2, 2), (3, 3), (4, 4), (None, 5), (None, 6)] open()It opens a file. (See the section "File Handling" for details.) basic syntax: open( filename [,mode [,bufsize]] ) pow()It returns x**y or (x**y) % z, depending on the number of arguments that are transported. basic syntax: pow( x, y [,z] ) raw_input()It reads from standard input (sys.stdin), returning the read data as a string. prompt is an optional text that can be displayed in the screen. basic syntax: raw_input( [prompt] ) reduce()It applies a function cumulatively to the items in sequence (implied loop), returning a single value. initializer is an optional starting value. basic syntax: reduce( function, sequence [,initializer] ) >>> import operator >>> a = [1,2,3] >>> print reduce(operator.add, a) 6 The equivalent Python code for this function is something like def reduce(func, list): ret = list[0] for x in list[1:]: ret = func(ret, x) return ret __import__()This is a function invoked by the import statement. To import a module, you just need to inform the module name. basic syntax: __import__( module_name [,globals() [, locals() [,from list]]] ) >>> modname = "string" >>> string = __import__(modname) >>> string reload()It reloads an already imported module. Internally, it calls the __import__ function. basic syntax: reload( module ) Sequence FunctionsThe next set is built-in functions that deal with sequences. range()It returns a list of numbers according to the transported information. basic syntax: variable = range( [initial_value,] final_value-1 [, step] ) >>> lst = range(1,5) >>> lst [1, 2, 3, 4] See the section "Data Structures" for details. xrange()It is similar to range(), but it doesn't assign the returned list to a variable, Therefore, it doesn't use as much memory, so you won't run out of memory by typing xrange(2000000000), for instance. basic syntax: xrange( [initial_value,] final_value-1 [, step] ) See the section "Data Structures" for details. len()It returns the length/number of elements of string. basic syntax: len( variablename ) max()It returns the maximum/largest element of sequence. >>> max(1, 2, 3) 3 >>> max("MY BRAIN HURTS") "Y" min()It returns the minimum/smallest element of sequence. >>> min("MY BRAIN HURTS") " " zip()It returns a list of tuples where each tuple contains the i-th element from each of the given sequences. This function generates a resulting list whose length is exactly the same as of the shortest given sequence. Note that, on the other hand, the function map(None, sequence1, sequence2, …) pads the resulting list with None when the sequences don't have the same length. basic syntax: zip( sequence1, sequence 2, sequence3, … ) Object ManipulationThe next set is built-in functions that deal with object handling. setattr()It sets a new value for object.name basic syntax: setattr( object, name, value ) getattr()It returns the attribute from object. This command is equivalent to object.attribute. basic syntax: getattr( object, attribute ) hasattr()It returns 1 if object has attribute, 0 if it doesn't. basic syntax: hasattr( object, attribute ) delattr()It deletes the attribute from object. This command is equivalent to del object.attribute. basic syntax: delattr( object, attribute ) type()It returns the type of object. >>> type("andre") <type "string"> dir()It returns a list of attribute names from the active namespace. object can be anything (a variable, a module, a class, and so on). callable()It returns 1 if object is callable. Otherwise, it returns 0. basic syntax: callable( object ) hash()It returns a hash value for object. id()It returns the system unique identifier of object. vars()It returns the symbol table of object or a dictionary from the local namespace. basic syntax: vars( [object] ) Mathematical/Logical FunctionsThe next set is built-in functions that deal with mathematical and logical operations. abs()It returns the absolute value of number. >>> abs(-12), abs(34), abs(+20.23), abs(-10.82) (12, 34, 20.23, 10.82) cmp()It returns -1 when x<y; 0 when x==y, 1 when x>y >>> cmp(10,20), cmp(25,25), cmp(30,25) (-1, 0, 1) round()It rounds number to the given number of decimals. Note that the provided number is rounded to an integer by default. basic syntax: round( number [,decimals] ) divmod()It returns a tuple (quotient, remainder), resulting in the expression dividend/divisor. basic syntax: divmod( dividend, divisor ) >>> divmod(25/3) (8, 1) Code FunctionsThe next set is built-in functions that deal with Python bytecode manipulation. eval()It evaluates the compiled code string object as if it were Python code, and returns the result. globals and locals define the namespaces for the operation. Note that eval can evaluate expressions only—not arbitrary statements. Therefore, eval('import string') won't work. basic syntax: eval( string [,globals [,locals]] ) >>> a = eval('2 * y + (20 / x)') exec()exec is a statement that executes a string containing Python code. globals and locals define the namespaces for the operation. basic syntax: exec string [in globals [,locals]] >>> a='for b in range(4):\n print b,\n' >>> exec a 0 1 2 3 execfile()It executes the statements included in the file provided. globals and locals define the namespaces for the operation. basic syntax: execfile( file [,globals[,locals]] ) >>> execfile("c:\\python\program2.py") You can redefine the global and the local namespaces for these functions by creating dictionaries, just like the next example shows. If you omit the values, the current environment namespace is always used. >>> globalsvar = {'x': 7} >>> execfile("c:\\python\\program2.py", globalsvar) compile()It compiles a code object ( string ) that optionally might be located in a file. The type value depends on the following: if string is a sequence of statements, type is "exec"; if string is a single expression, type is "eval"; and if string is an executable statement, type is "single". basic syntax: compile( string, file, type ) >>> a = "for i in range(0,10): print i," >>> b = compile(a, "", "exec") >>> exec b 0 1 2 3 4 5 6 7 8 9 >>> a = "123 * 2" >>> c = compile(a, "", "eval") >>> d = eval(c) >>> d 246 Tip
If you need to evaluate or execute the same code many times in your application, the application will get more optimized if you compile all the source code first. Type ConversionThe next set is built-in functions that deal with data type conversion. int()It converts object to an integer number. long()It converts object to a long integer. As of Python 2.0, the functions int() and long() have an optional base argument, which can be used when the first argument is a string. Note that if you try to use this second argument with a value that is not a string, you get a TypeError exception message. The following examples demonstrate what happens when we use this argument: int('450', 10) returns 450, and int('25', 16) returns 37. float()It converts object to a floating-point number. complex()It creates a complex number in the format ( real number + imaginary number) basic syntax: complex( real [,imaginary] ) str()It returns the printable representation of object. It returns the same value that a " print object " statement does. repr()It is equivalent to the enclosing backticks ``. It returns an expression that can be evaluated. You can use either repr() or `` to get the representation of an escape character. >>> repr('spam\n') "'spam\\012'" tuple()It creates a tuple based on sequence. basic syntax: tuple( sequence ) list()It creates a list based on sequence. basic syntax: list( sequence ) chr()It converts an integer into one character. ord()It returns the ASCII value of string. hex()It converts an object into a hexadecimal value. oct()It converts an object into an octal value. unicode()This function takes an 8-bit string and creates a Unicode string. basic syntax: unicode( string [, encoding] [, errors] ) encoding and errors are some additional arguments that you can also provide to the function. The first one is a string that names the encoding to use. errors defines what to do when an invalid character is used for the current encoding. You have three options for values here: strict causes an exception to be raised on any encoding error, ignore simply ignores any errors, and replace replaces the invalid character with the official replacement character U+FFFD whenever it finds any problem. unichr()This function returns a 1-length Unicode string containing the given character. basic syntax: unichr( character )
|
© 2002, O'Reilly & Associates, Inc. |