Python Reference Manual
Important built-in functions of expressions
Description of the evaluate function: numabs (numbers) returns the absolute value of a number. apply (func [, arg [, kwargs]) calls a given function. You can choose to provide the parameter all (iterable) if all iterable elements are True, True is returned. Otherwise, Falseany (iterable) is returned. If any iterable element is True, True is returned. Otherwise, Falsebasestring () str and unicode abstract superclass are returned, depends on the Boolean value c of obj Allable (obj) check whether the object can call char (number) to return ASCII for the given character classmethod (func) using an instance method to create a class method cmp (x, y) to compare x, y. X
Y: returns a positive number; x = y, returns 0 complex (real [, imag]) returns the plural delattr ([mapping-or-sequence]) of the given real part. delete a given attribute dict ([mapping-or-sequence]) from a given object to construct a dictionary. You can select a list consisting of key-value pairs. You can also use the keyword parameter to call dir (object) to list most of the features of a given object. divmod (a, B) returns (a/B, a % B) enumerate (iterable) iterate all iterable items into eval (string [, globals [, locals]) to calculate the string containing the expression. Execfile (file [, globals [, locals]) can be selected for a given global or local scope to execute a Python file, optional. Create a file with the specified file name in the specified global or local scope (filename [, mode [, bufsize, you can choose to use the given mode and cache size float (object) to convert string or value to floating point frozenset ([iterable]) to create an immutable set, this means that it cannot be added to other sets. getattr (object, name [, default]) returns the value of the feature specified in the given object. You can select the default value globals () the returned result indicates that the dictionary hasattr (object, name) in the current scope checks whether the given object has the specified attribute help ([object]) to call the built-in help system, or print the help information of the given object hex (number) to convert the number to the string id (objec T) returns the unique IDinput ([prompt]) of the given object, which is equivalent to eval (raw_input (prompt) int (object [, radix]). converts a string or number to an integer isinstance (object, classinfo) check whether the given object is an instance of the given classinfo value. classinfo can be a class object, a type object, or a class object and the ancestor issubclass (class1, class2) of the type object) check whether class1 is a subclass of class2. iter (object [, sentinel]) returns an iteration object, which can be used as the object_iter () iterator of the iteration sequence, or provides an sentinel, the iterator calls the object in each iteration, and returns the sentinellen (object) to return the length of the given object list ([object]) to construct a list locals () returns the dictionary long (Object [, radix]) converts a string or number to a long integer map (function, seq1 ,...) create a list of values returned when the given function func is applied to each item in the list seq (obj1 [, obj2]...) if obj1 is a non-empty sequence, the maximum element is returned; otherwise, the maximum value mix (obj1 [, obj2]...) of the provided parameters is returned. if obj1 is a non-empty sequence, the smallest element is returned; otherwise, the minimum value of the provided parameter object () is returned. The oct (number) instance of the base Object of all new classes is returned) convert an integer to the alias of the open (filename [, mode [, bufsize]) file string in octal format. Use open instead of filepow (x, y [, z]) returns the yth power of x. You can select the ASCII value range ([start,] stop [, step]) That is returned to the order character in the form of zord (char). use the given start value and end value Value to create the value range property (fget [, fset [, fdel [, doc]) using a set of accessors to create the property raw_input ([prompt]) return the data entered by the user as a string. You can use the given prompt promptreduce (func, seq [, initializer]) to incrementally apply all the values in the sequence to the given function, using the cumulative result as all the items of the first parameter as the second parameter, you can select the given starting value reload (module) to reload a loaded module and return it to repr (object) returns the string representing the object. It is generally used as the eval parameter to return the reverse iterator round (float [, n]) of the sequence using reversed (object) to round the given floating point, after the decimal point, keep the n-bit set ([iterable]). Return the setattr (object, name, value) Element set From iterable. set the value of the specified attribute of the given object to the given value. Sorted (iterable [, cmp] [, key] [, reverse]) returns a new sorted list from iterable, the optional parameters are the same as those in the list method sort. staticmethod (func) returns the formatted string sum (seq [, return the super (type [, obj/type]) of a series of numbers added to the optional start parameter. Return the super class tuple ([sequence]) of the given type to construct a ancestor, you can choose to use the same sequence item type (object) to return the type (name, bases, dict) of the given object to use the given name, the base class and scope return a New Type object unichr (number) the Unicode version of chr unicode (object [, encoding [, errors]) returns the given pair The Unicode encoding version of the image. You can specify the encoding mode and error handling mode vars ([object]) to return the dictionary representing the local effect, or xrange ([start,] stop [, step]) is similar to range, but the returned object uses less memory and is only used for iterative zip (seq1 ,...) returns the list of ancestor. Each ancestor includes an item in a given sequence. The minimum return length is used.
List Method
Else method description else L. append (obj) is equivalent to L [len (L): len (L)] = [obj] L. count (obj) returns the value of L [I] = I in obj. extend (obj) is equivalent to L [len (L): len (L)] = seqL. index (obj) returns the smallest I in L [I] = obj. If no value exists, the ValueError exception is triggered. insert (index, obj) index> 0, equivalent to L [index: Index] = [obj], index <0, insert at the beginning of the List L. pop ([index]) removes and returns the specified index (-1 by default) L. remove (obj) is equivalent to L [L. index (obj)] L. sort ([cmp] [, key] [, reverse]) sorts the items in L in situ. You can use the comparison function cmp to create the key function and reverse flag for sorting.
Dictionary Method
Define method description D. clear () Remove all items in D. copy () returns the copy of D. fromkeys (seq [, val]) returns the dictionary of keys obtained from seq and values set to val. Class method call D. get (key [, default]) if D [key] exists, return it; otherwise, return the given default value NoneD. has_key (key) Check whether D has a given key keyD. items () returns the (Key, value) pair List D that represents item D. iteritems () from D. the (Key, value) pair returned by items () returns an iteratable Object D. iterkeys () returns an iteratable Object D from the D key. itervalues () returns an iteratable Object D from the value of D. keys () returns the list of keys D. pop (key [, d]) removes and returns the value D corresponding to the given key or given default value D. popitem () removes any item from D and uses it as a (Key, value) pair to return D. setdefault (key [, default]) if D [key] exists, return it; otherwise, return the default value NoneD. update (other) adds each item in other to D. D. values () returns the list of values in D.
String Method
------------------------------------------------------------------------------------------------- S. capitalize () returns the copy of the string in uppercase S. center (width [, fillchar]) returns a string of max (len (S), width), center S, and fills S with fillchar on both sides. count (sub [, start [, end]) calculates the number of times the sub-string appears. You can set the search range to S [start: end] S. decode ([encoding [, error]) returns characters using the given encoding method The decoded version of the string. error specifies the error handling method S. endswith (suffix [start [, end]) checks whether S ends with suffix. You can specify [start: end] to select the matching range S. expandtabs ([tabsize]) returns a copy of the string. The tab character is extended by space. You can select tabsizeS. find (sun [, start [, end]) returns the first index of the sub-string. If it does not exist, it is-1. You can select the search range S. index (sub [, start [, end]) returns the first index of the sub-string. If no index exists, a ValueError exception is thrown. s. isalnum () checks whether the string is composed of letters or numbers. isalpha () checks whether the string is composed of letters and characters S. isdigit () checks whether the string is composed of digits. islower () checks whether the string is composed of lowercase letters S. isspace () checks whether the string is composed of spaces S. istitle () Checks strings with uppercase letters S. isupper () checks whether the string is composed of uppercase letters S. join (sequence) returns the string element of sequence connected by S. ljust (width [, fillchar]) returns the string with the left alignment of the S copy. The length is max (len (S), W), and The fillchar on the right is filled with S. lower () returns a lowercase copy of all strings. lstrip ([char]) removes all char from the left, which is removed by default (space, tab, \ n) S. partition (seq) searches for seq in the string and returns S. replace (old, new [, max]) replace new with oglad. max S can be replaced at most. rfind (sub [, start [, end]) returns the last index of the sub. If the index does not exist, the value-1 is returned. The search range is S [start: end] S. rindex (sub [, start [, end]) returns The last index of the sub. If the index does not exist, a ValueError exception is thrown. S. rjust (width [, fillchar]) returns the right-aligned string of the S copy. The length is max (len (S), W), and the left-side fillchar is filled with S. rpartition (seq) is the same as Partition, but search for S. rstip ([char]) removes all char from the right. By default, it is removed (space, tab, \ n) S. rsplit (sep [, maxsplit]) is the same as split, but when maxsplit is used, S is counted from right to left. split (sep [, maxsplit]) uses sep as the delimiter. You can use maxsplit to specify the maximum score S. zfill (width) fills the width character S with 0 on the left side of S. upper () returns a copy of S. All characters are uppercase S. splitlines ([keepends]) returns the list of all rows in S. You can choose whether to include the line break S. startswith (prefix [, start [, end]) checks whether S starts with prefix. The range S can be defined using [start, end. strip ([chars]) removes chars characters from all strings. By default, strip removes (spaces, tab, \ n) S. swapcase () returns a copy of S, all case-insensitive S. title () returns a copy of S. All words start with an uppercase letter. translate (table [, deletechars]) returns a copy of S. All characters are converted using table. You can delete all characters that appear in deletechars.
Simple statement
A simple statement consists of a logical line.
Expression statement expressions can also be statements. This is especially true if the expression is a function call or document string.
"This module contains SPAM-related functions"
AssertionError is thrown if the condition is true. If the condition is false, AssertionError is thrown.
# True: >>> age = 20 >>> assert age >=12, 'The age under 12 is not allowed! '# False: >>> assert age >=40, 'The age must over 40! 'Traceback (most recent call last): File"
", Line 1, in
AssertionError: The age must over 40!
The value assignment statement binds the variable to the value. Multiple variables can be assigned values through the queue unpacking method, and replication can also be chained.
>>> Name, age = 'Jerry ', 38 # sequence unpacking >>>> x = y = z = 42 # chained assignment >>> x = 42 # simple assignment
You can use operators to add values to values in an incremental assignment statement. Operators can be applied to existing variable values and new values, and then the variables are rebound to the results.
>>> x *= 2 # x = x * 2>>> x += 5 # x = x + 5
The pass statement has no operation, so you do not need to do anything. A placeholder or statement that does not need to do anything
try: x.nameexcept AttributeError: passelse: print 'Hello', x.name
The del statement is used to unbind variables and features and remove a part of the data structure. But it cannot be used to directly delete a value, because the value can only be deleted through garbage collection.
Del x # unbind the variable del seq [4] # Delete the sequence element del seq [4:] # Delete the sequence slice del map ['foo'] # Delete the ing item in the dictionary
Print statement: This statement writes one or more values to a given stream. By default, sys. stdout. adds a linefeed unless it ends with a comma.
>>> Print 'hello, World! '# Convert 'hello, World! \ N' is written to sys. stdout >>> print 1, 2, 3 # Write '1 2 3 \ n' to sys. stdout> print> somefile, 'xyz' # Write 'xyz' to somefile> print 42, # Write '42' to sys. stdout
Return Statement
The return Statement terminates the function operation and returns the value. If no return value is provided, None is returned.
>>> Return # return None from the current function >>> return 42 # return 42 >>> return 1, 2, 3 # Return (1, 2, 3) from the current function)
Yield statement
The yield statement temporarily terminates the execution of the generator and generates a value. A generator is a form of iterator that can be used with other objects for a for loop.
Yielda 42 # returns 42 from the current function
Raise statement
The raise statement raises an exception. You can call it without parameters (in the limit t clause, the caught exception is thrown again)
You can also subclass Exception and provide optional parameters (in this case, an instance is constructed), or use an instance of the Exception subclass.
Raise # can only be used for raise IndexErrorraise IndexError, 'index out of bounds' raise IndexError ('index out of bounds') in the except T clause ')
Break statement
The break statement ends the current for or while loop and immediately executes the statement after the loop.
while True: line = file.readline() if not line: break print line
Continue statement
The contineu statement terminates the iteration in the current loop, but does not completely terminate the loop. Instead, it continues execution from the beginning of the next iteration.
while True: line = file.readline() if not line: break if line.isspace(): continue print line
Import Statement
The import Statement is used to import names (bound to functions, classes, or variables) from external modules ).
This also includes the from _ ure _ import * Statement. This statement is used to import standard features in future Python versions.
import mathfrom math import sqrtfrom math import sqrt as squarerootfrom math import *
Global Statement
The global statement is used to mark a variable as a global variable. It can allow statements in the function to re-bind global variables.
The use of global statements is generally considered to be a poor programming style, and should be avoided if possible.
count = 1def inc(): global count count += 1
Exec statement
The exec statement is used to execute a string containing a Python statement. You can select a given global and local namespace (dictionary ).
Exec 'print "Hello, World! "'Exec 'X = 2' in myglobals, mylocals # mygolobals and mylocals are both dictionaries.
Lambda statements
One type of function in Python, no variable, no return, simple and convenient.
Lambda x, y: x ** 2 + y, (1, 2) # colon segmentation, the preceding variable, the return value
Compound statement compound statement includes other statement Blocks
If statement
If statements are used for conditional execution. They can include elif and else statements.
if x < 10: print 'Less than 10'elif 10 <= x <= 20: print 'Less than 20'else: print 'More than 20'
While statement
The while statement is used for repeated execution when the given condition is true. It can include the else clause (executed when the loop ends normally without a break or return statement)
x = 1while x < 100: x *= 2print x
For statement
The for statement is used to repeatedly execute a loop on the elements of a sequence or other iteratable objects (the object has the _ iter _ method returned by the iterator.
It can include an else clause (executed when the loop ends normally without any break or return statement)
for i in range(10, 0, -1): print iprint 'Ignition!'
Try statement
The try statement is used to close a piece of code that may have one or more exceptions, so that the program can catch these exceptions and handle exceptions when they are caught.
A try statement can contain multiple distinct T clauses to handle exceptions and multiple finally clauses (Statements executed in any case are used for cleanup)
try: 1/0except ZeroDivisionError: print "Can't divide anything by zero."finally: print 'Done trying to calculate 1/0'
With statement
The with statement uses the so-called context manager to encapsulate the code block, allowing the context manager to perform some settings and cleanup operations.
For example, files can be used as context managers, and they can close themselves as part of cleaning.
NOTE: In PYTHON2.5, use from _ ure _ import with_statement to import with statements.
With open('NOTE.txt ') as myfile: dosomething (myfile) # close the file here
Function Definition
Function definitions are used to create function objects and bind global or local variables to function objects.
def double(x): return x * 2
Class Definition
Class definition is used to create class objects and bind global or local variables to class objects.
class Doubler: def __init__(self,value): self.value = value def double(self): self.value *= 2
It is used to record the convenient "memos" that can be used to update memory when you start using PYTHON programming. For a complete reference manual, see the Python standard documentation.
Https://www.python.org/doc/