Python reference manual, python reference manual chm

Source: Internet
Author: User
Tags iterable

Python reference manual, python reference manual chm
Important built-in functions of expressions

# Function # description ------------------------------------------------------------------------------------------------- abs (numbers) # returns the absolute value of A number apply (func [, arg [, kwargs]) # calls a given function, optional parameter all (iterable) # True is returned if all iterable elements are True; otherwise, Falseany (iterable) is returned. # True is returned if any iterable element is True, otherwise, return Falsebasestring () # str and unicode abstract superclass, depending on the Boolean value of obj callable (obj) # Check whether the object can call char (number) # Return ASCII for the given character classmethod (func) # use an instance method to create a class method cmp (x, y) # Compare x and y. X <y: Return negative number; x> y: Return positive number; x = y, return 0 complex (real [, imag]) # Return the plural delattr ([mapping-or-sequence]) of a given real part # delete a given attribute dict ([mapping-or-sequence]) from a given object # construct a dictionary, you can select a list structure composed of key-value pairs. You can also use the keyword parameter to call dir (object) # list most of the features of a given object divmod (a, B) # Return (a/B, a % B) enumerate (iterable) # iterate all iterable items eval (string [, globals [, locals]) # Calculate the string containing the expression. Execfile (file [, globals [, locals]) can be selected for a given global or local scope # execute a Python file, optional. Perform file (filename [, mode [, bufsize]) in a given global or local scope # create a file with a given file name, you can choose to use the given mode and cache size float (object) # convert string or value to float frozenset ([iterable]) # 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 () # Return hasattr (object, name) for the current scope # check whether a given object has a specified attribute help ([object]) # Call the built-in help system, or print the help information of the given object hex (number) # convert the number to a hexadecimal character String id (object) # Return the unique IDinput ([prompt]) of the given object # equivalent to eval (raw_input (prompt) int (object [, radix]) # converting 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 or type object issubclass (class1, class2) # Check whether class1 is a subclass of class2 iter (object [, sentinel]) # Return an iteration object, which can be used for the object_iter () iterator len (object) of the iteration sequence) # Return the length list of the given object ([object]) # construct a list locals () # Return the dictionary long (object [, radix]) that indicates the current local scope. # convert 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 object () of the provided parameters is returned. # The oct (number) instance of the base Object of all new classes is returned) # convert an integer to the string open (filename [, mode [, bufsize]) in octal format # file alias. When opening a file, use open instead of filepow (x, y [, z]) # returns x to the power of y. You can select zord (char) # The ASCII value range ([start,] stop [, step]) # Use the given start value and end value to create the value range property (fget [, fset [, fdel [, Doc]) # create the attribute raw_input ([prompt]) through a set of accessors # Return the user input data as a string, you can choose to use the given prompt promptreduce (func, seq [, initializer]) # apply all the given functions to the incremental sequence, and use the accumulated results as the first parameter, all items are used as the second parameter. You can select the given starting value reload (module) # reload a loaded module and return it to repr (object) # Return the string representing the object, generally, as eval parameters, reversed (object) # The Reverse iterator round (float [, n]) that returns the sequence # rounds the given floating point, keep n-digit set ([iterable]) after decimal point # Return setattr (object, name, value), an element set generated from iterable) # Set the value of the specified attribute of the given object to the given value sorted (iterable [, cmp] [, k Ey] [, reverse]) # Return a list after sorting from iterable. The optional parameters are the same as those in the list method sort. staticmethod (func) # create a static class method str (object) from an instance method # Return the formatted string sum (seq [, start]) of the given object. # Return the super (type [, obj/type]) of a series of numbers added to the optional parameter start # Return the super class tuple ([sequence]) of the given type # construct a ancestor, you can select the same type (object) as sequence # Return the type (name, bases, dict) of the given object # Use the given name, the base class and scope return a New Type object unichr (number) # Unicode version of chr unicode (object [, encoding [, errors]) # returns the Unicode encoding version of the given object, The encoding mode and error handling mode vars ([object]) can be specified. # The returned value indicates the dictionary that is locally applied or xrange ([start,] stop [, step]) # similar to range, but the returned object uses less memory and is only used for iterative zip (seq1 ,...) # Return the list of ancestor. Each ancestor includes an item in a given sequence. The minimum return length is used.
List Method

# Method # description L. append (obj) # equivalent to L [len (L): len (L)] = [obj] L. count (obj) # Return the value of L [I] = I in obj. extend (obj) # 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]) # Remove and return the item of the given index (-1 by default) L. remove (obj) # equivalent to L [ L. index (obj)] L. sort ([cmp] [, key] [, reverse]) # sort the items in L in situ. The comparison function cmp can be provided to create the key function and reverse flag for sorting.
Dictionary Method

# 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 () # Return the list of (Key, value) pairs that represent item D. iteritems () # from D. the (Key, value) pair returned by items () returns an iteratable Object D. iterkeys () # Return an iteratable Object D from the D key. itervalues () # Return an iteratable Object D from the value of D. keys () # returns the list of keys D. pop (key [, d]) # Remove and return the value D corresponding to the given key or given default value D. popitem () # Remove any item from D and use 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) # add each item in other to D. D. values () # returns the list of values in D.
String Method

# Method # description of ipvs. capitalize () # returns the copy of the string in uppercase S. center (width [, fillchar]) # Return a length of max (len (S), width), center S, and fill S with fillchar on both sides. count (sub [, start [, end]) # calculate the number of times the sub-string appears. You can set the search range to S [start: end] S. decode ([encoding [, error]) # Return the decoded version of the string using the given encoding method. error specifies the error processing method S. endswith (suffix [start [, end]) # Check 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 the sub-string does not exist, the value 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 error is thrown. s. isalnum () # Check whether the string is composed of letters or numbers. isalpha () # Check whether the string is composed of letters and characters. isdigit () # Check whether the string is composed of numeric characters S. islower () # Check whether the string is composed of lowercase letters S. isspace () # Check whether the string is composed of spaces. istitle () # Check the string with uppercase letters S. isupper () # Check whether the string is composed of uppercase letters S. join (sequence) # Return the sequence String elements 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]) # Remove all char to the left. By default, all char S are removed (space, tab, \ n. partition (seq) # search for seq in the string and return 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. fill ust (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) # Same as Partition, but search for S. rstip ([char]) # Remove all char to the right. By default, all char (space, tab, \ n) S are removed. rsplit (sep [, maxsplit]) # Count S from right to left when using maxsplit. split (sep [, maxsplit]) # Use sep as the delimiter. You can use maxsplit to specify the maximum score (S. zfill (width) # Fill 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]) # Return the list of all rows in S. You can choose whether to include the line break S. startswith (prefix [, start [, end]) # Check whether S starts with prefix. The range S can be defined using [start, end. strip ([chars]) # removes characters containing chars from all strings. By default, strip (space, tab, \ n) S is removed. swapcase () # returns a copy of S, which is case-insensitive. 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.
Basic Data Type

# Type # Description Example ------------------------------------------------------ Integer # number of decimal parts 42 Long Integer # large Integer 42 LFloat # number of decimal parts 42.5, 42.5e-2 Complex # Real Number and imaginary number and 4 + 3j, 42 jString # immutable Character Sequence 'foo', "bar", "" abc """, r' \ n' Unicode # unchangeable Unicode sequence u 'foo', u "bar", u "abc """

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 "<stdin>", line 1, in <module> 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
New Features of Python3.0

# Version # new features 01. python 3.0: # print is a function 02. python 3.0: # force encoding of text files 03. python 3.0: # The zip, map, and filter functions return to the iterator 04. python 3.0: # dict. keys (), dict. values () and dict. items () returns the view instead of the List 05. python 3.0: # cmp parameters are no longer used for sorted and list. sort, replace 06 with key. python 3.0: # division to true division 1/2 = 0.507.Python 3.0: # Only one string type str, equivalent to the unicode type 08 in Python2.x. python 3.0 :# Basestring class removed 09. python 3.0: # The new bytes type is used to represent binary data and encoded text 10. python 3.0: # bytes written as B "abc" 11. python 3.0: # UTF-8 is the default Python source file encoding method. Non-ASCII identifier 12 can be used. python 3.0: # StringIO and cStringIO are composed of io. stringIO and io. bytesIO instead of 13. python 3.0: # The new built-in string formatting method replaces the % Operator 14. python 3.0: # functions can annotate their own parameters and return values. 15. python 3.0: # Use raise Exception (args) instead of raise Exception, args16.Python 3.0: # Use counter t MyException as identifier instead of counter t MyException, identifier17.Python 3.0: # the classic and old classes are removed 18. python 3.0: # Foo (Base, metaclass = Meta): used to set the original class 19. python 3.0: # Add abstract classes @ abstractmethod and @ abst Ractproperty+python 3.0: # added class modifiers, similar to function modifiers 21. python 3.0: # Use the repr function 22 instead. python 3.0: # <> the operators are no longer used. They are all used! = 23. python 3.0: # True, False, None, as, and with are keywords, meaning 24 variable names cannot be used. python 3.0: # The long type is renamed to int, which is now the only integer without L25.Python 3.0: # sys. the maxint is removed, and the maximum value is no longer 26. python 3.0: # x <y Returns Error 27 if x and y belong to different types. python 3.0 :#__ getslice _ and similar functions are removed. You can use the multipart object to call _ getitem _ 28. python 3.0: # The parameter can be used as a dedicated keyword 29. python 3.0: # After using nonloacl x, you can assign a value of 30 to x in the external scope. python 3.0: # raw_input is renamed as input. Use eval (input () to obtain the original input function 31. Python 3.0: # rename xrange to range32.Python 3.0: # The unpackage feature of the original parameter is removed. Def foo (a, (B, c): 33. Python 3.0: # The next function in the iterator is renamed as x. _ next __. Next (x) calls x. _ next _ 34. Python 3.0: # adds the octal literal. Replacing 066635. Python 3.0 with 0o666: # adds the binary literal. 0b1010 = 10. Bin () functions are similar to hex () and oct () 36. python 3.0: # The asterisk iterator unpack function is added. For parameters a and B, * rest = seq or * rest. a = seq37.Python 3.0: # The super function can be called without parameters, and the behavior will be correct 38. python 3.0: # string. letters and related functions are removed. Replacing 39. Python 3.0: # apply with string. ascii_letters is removed. Replace apply (f. x) 40. Python 3.0: # callable with f (* x. Use hasattr (f, "_ call _") to replace callable (f) 41. Python 3.0: # The coerce function is removed 42. Python 3.0: # execfile is removed. Use exec to replace 43. Python 3.0: # The file object is removed. 44. Python 3.0: # The reduce function is moved to the functools module. 45. Python 3.0: # The reload function is removed. Use exec to replace 46. Python 3.0: # dict. has_key is removed. Use k in d instead of d. has_key (k)


Note: It is used to record the convenient "Memorandum" that can be used to update memory when you start to use PYTHON programming. For a complete reference manual, see the Python standard documentation.

Https://www.python.org/doc/




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.