Python notes

Dive Into Python

      译文版 (5.4):2005年12月—月—2006年4月 (update-060425)

在 Windows 上,安装 Python 有两种选择。

ActivePython -- http://www.activestate.com/Products/ActivePython/

      ActiveState 制作的 ActivePython 是专门针对 是专门针对 是专门针对 是专门针对 Windows 的 Python 套件,它包含套件,它包含 套件,它包含 了一个完整的 了一个完整的 了一个完整的 Python 发布、一个适用于 发布、一个适用于 发布、一个适用于 Python 编程的 编程的 IDE 以及一些 以及一些 以及一些 以及一些 以及一些 Python 的 Windows 扩展,提供了全部的访问 扩展,提供了全部的访问 扩展,提供了全部的访问 扩展,提供了全部的访问 扩展,提供了全部的访问 扩展,提供了全部的访问 扩展,提供了全部的访问 Windows APIs 的服务,以及 的服务,以及 的服务,以及 的服务,以及 的服务,以及 Windows 注册表的信息。

选项 2 :安装来自 Python.org

http://www.python.org/ftp/python/

 

 

The Python tutorial 3.0

    Release: 3.0
    Date: October 31, 2008


Whetting Your Appetite

    Python is an interpreted language; no compilation and linking is necessary.
   
    Python enables programs to be written compactly and readably for several reasons:
        the high-level data types allow you to express complex operations in a single statement;
        statement grouping is done by indentation instead of beginning and ending brackets;
        no variable or argument declarations are necessary.
   
    By the way, the language is named after the BBC show "Monty Python's Flying Circus" and has nothing to do with nasty reptiles.

Using the Python Interpreter

    python
   
    python -c command [arg] ...
   
    python -m module [arg] ...
   
    Argument Passing -- sys.argv
        Its length is at least one; when no script and no arguments are given, sys.argv[0] is an empty string.
        When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter¡¯s option processing but left in sys.argv for the command or module to handle.

    By default, Python source files are treated as encoded in UTF-8.
        specify a different encoding for source files, put one more special comment line right after the #! line to define the source file encoding:
            # -- coding: encoding --        For example: # -- coding: cp-1252 --

An Informal Introduction to Python
    input and output are distinguished by the presence or absence of prompts (>>> and ...):
        lines that do not begin with a prompt are output from the interpreter.
       
    Comments in Python start with the hash character, '#', and extend to the end of the physical line.
        A comment may appear at the start of a line or following whitespace or code, but not within a string literal.
        A hash character within a string literal is just a hash character.
       
     Using Python as a Calculator  
        the operators +, -, * and / work just like in most other languages;
        To do integer division and get an integer result, discarding any fractional result, there is another operator, //: 7//3=2; 7//-3=-3;
    
     Strings
        They can be enclosed in single quotes or double quotes:
        The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it¡¯s enclosed in single quotes.
        Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.
        Strings can be concatenated (glued together) with the + operator, and repeated with *:
        Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:
        Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type;
        (Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:)
        Indices may be negative numbers, to start counting from the right.
            For example: word[-1]     # The last character

    About Unicode
        Starting with Python 3.0 all strings support Unicode.
       
    Lists
        written as a list of comma-separated values (items) between square brackets.
        List items need not all have the same type. >>> a = ['spam', 'eggs', 100, 1234]
        Unlike strings, which are immutable, it is possible to change individual elements of a list:    a[2] = a[2] + 23
        The built-in function len() also applies to lists:  >>> len(a)
        It is possible to nest lists (create lists containing other lists), for example:
            >>> q = [2, 3]
            >>> p = [1, q, 4]
        You can add something to the end of the list:
            >>> p[1].append('xtra')
            >>> p
            [1, [2, 3, 'xtra'], 4]
           
    Note that each line within a basic block must be indented by the same amount.

More Control Flow Tools
    while
        while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

    if
        if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

   
    for
        for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

    It is not safe to modify the sequence being iterated over in the loop.
   
    The range() Function:
        >>> for i in range(len(a)):
        ...     print(i, a[i])
       
    The function list():
        >>> list(range(5))
        [0, 1, 2, 3, 4]
       
    break and continue Statements, and else Clauses on Loops
        Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:  
   
    pass Statements
        when a statement is required syntactically
           
    Defining Functions
        The keyword def introduces a function definition.   >>> def fib(n):
        The first statement of the function body can optionally be a string literal; this string literal is the function¡¯s documentation string, or docstring.
        general renaming mechanism: >>> f = fib
       
        The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a procedure also returns None.
   
    More on Defining Functions
        specify a default value for one or more arguments: def ask_ok(prompt, retries=4, complaint=¡¯Yes or no, please!¡¯):
            This function can be called either like this: ask_ok('Do you really want to quit?') or like this: ask_ok('OK to overwrite the file?', 2).   
        The default values are evaluated at the point of function definition in the defining scope;
        Functions can also be called using keyword arguments of the form keyword = value.
        a function can be called with an arbitrary number of arguments.
       
    Documentation Strings    
               

Data Structures
    Tuples and Sequences
        A tuple consists of a number of values separated by commas, for instance: >>> t = 12345, 54321, 'hello!'
        Tuples, like strings, are immutable;
   
    More on Lists
        list.append(x)
        list.extend(L)
        list.insert(i, x)
        list.remove(x)
        list.pop([i]): the parameter is optional;
        list.index(x)
        list.count(x)
        list.sort()
        list.reverse()
       
        Using Lists as Stacks
            append()
            pop()    
       
        Using Lists as Queues
            append()
            pop(0)
       
        List Comprehensions
           
           
        The del statement
            remove an item from a list given its index instead of its value:     del a[0]
            remove slices from a list: del a[2:4]
            clear the entire list: del a[:]
            delete entire variables: del a

    Sets -- an unordered collection with no duplicate elements
        Curly braces {} or the set() function can be use to create sets.
        To create an empty set you have to use set(), not {};
       
    Dictionaries: like associative arrays in Perl
        storing a value with some key and extracting the value given the key.
        keys()
        in: To check whether a single key is in the dictionary, use the in keyword.
        dict()
       
        Looping Techniques
            items(): When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
            enumerate(): When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
            zip(): To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
            reversesd(): To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
            sorted()
   
    More on Conditions
        in and not in
        is and is not : compare whether two objects are really the same object;
        Comparisons can be chained: a < b == c tests whether a is less than b and moreover b equals c.
        and, or, not
        The Boolean operators and and or are so-called short-circuit operators
       
    Comparing Sequences and Other Types
        if the first two items are equal, the next two items are compared


 

Modules
    A module is a file containing Python definitions and statements.
    Within a module, the module’s name (as a string) is available as the value of the global variable __name__ .
        >>> import functions
        >>> functions.__name__
        'functions'
    More on Modules
        Executable statements in a module: to initialize the module. They are executed only the first time the module is imported somewhere. [1]
       
        A variant of the import statement: do not use this facility as it possibly hides some things you have already defined.
        >>> from fibo import fib, fib2
        >>> from fibo import *

    Executing modules as scripts
        the __name__ set to "__main__".
             if __name__ == "__main__":
                import sys
                fib(int(sys.argv[1]))

    The Module Search Path
        searching sequence: the current directory -> the environment variable PYTHONPATH -> an installation-dependent default path
        Actually, modules are searched in the list of directories given by the variable sys.path.           

    “Compiled” Python files
        speed-up of the start-up time: .pyc; “byte-compiled”       
 
    Standard Modules
        sys: sys.ps1 and sys.ps2: define the strings used as primary and secondary prompts in interactive mode;

    The dir() Function        
        The built-in function dir() is used to find out which names a module defines.
        Without arguments, dir() lists the names you have defined currently.
        dir() does not list the names of built-in functions and variables.
            >>> import builtins
            >>> dir(builtins)

    Packages
        Packages are a way of structuring Python’s module namespace by using “dotted module names”.
        The __init__.py files are required to make Python treat the directories as containing packages;
        a package’s __init__.py code defines a list named __all__.
       
    Intra-package References
        from . import echo
        from .. import formats
        from ..filters import equalizer
       
    Packages in Multiple Directories
        __path__
       
       
       
Input and Output

    Fancier Output Formatting
        The % operator: like a sprintf-style format string
            >>> import math
            >>> print('The value of PI is approximately %5.3f.' % math.pi)
            The value of PI is approximately 3.142.

       
        Python has ways to convert any value to a string: pass it to the repr() or str() functions.
        The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter.
       
        rjust(): right-justifies a string in a field of a given width by padding it with spaces on the left.
        ljust() and center().
        zfill(): pads a numeric string on the left with zeros.
   

    Reading and Writing Files
        open(): open(filename, mode)
            open(file[, mode='r'[, buffering=None[, encoding=None[, errors=None[, newline=None[, closefd=True]]]]]])?
            The available modes are: The default mode is 'rt' (open for reading text).
                Character Meaning
                'r' open for reading (default)
                'w' open for writing, truncating the file first
                'a' open for writing, appending to the end of the file if it exists
                'b' binary mode
                't' text mode (default)
                '+' open a disk file for updating (reading and writing)
                'U' universal newline mode (for backwards compatibility; unneeded for new code)

    Methods of File Objects
        f.read(size):  
            When size is omitted or negative, the entire contents of the file will be read and returned;
            If the end of the file has been reached, f.read() will return an empty string ("").
        f.readline():  reads a single line from the file; a newline character (\n) is left at the end;
            >>> for line in f:
                    print(line, end='')
        f.write(string) writes the contents of string to the file, returning None.
        f.tell(): returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file.
        f.seek(offset[,from_what]): to change the file object’s position.
        f.close()
       
    The pickle Module
        the read() method only returns strings
        pickling and unpickling:    the technical term for this is a persistent object.
            pickle.dump(x, f)
            x = pickle.load(f) 


Errors and Exceptions
    Syntax Errors
    Exceptions
        The class hierarchy for built-in exceptions is:
        BaseException
         +-- SystemExit
         +-- KeyboardInterrupt
         +-- GeneratorExit
         +-- Exception
              +-- StopIteration
              +-- ArithmeticError
              |    +-- FloatingPointError
              |    +-- OverflowError
              |    +-- ZeroDivisionError
              +-- AssertionError
              +-- AttributeError
              +-- BufferError
              +-- EnvironmentError
              |    +-- IOError
              |    +-- OSError
              |         +-- WindowsError (Windows)
              |         +-- VMSError (VMS)
              +-- EOFError
              +-- ImportError
              +-- LookupError
              |    +-- IndexError
              |    +-- KeyError
              +-- MemoryError
              +-- NameError
              |    +-- UnboundLocalError
              +-- ReferenceError
              +-- RuntimeError
              |    +-- NotImplementedError
              +-- SyntaxError
              |    +-- IndentationError
              |         +-- TabError
              +-- SystemError
              +-- TypeError
              +-- ValueError
              |    +-- UnicodeError
              |         +-- UnicodeDecodeError
              |         +-- UnicodeEncodeError
              |         +-- UnicodeTranslateError
              +-- Warning
                   +-- DeprecationWarning
                   +-- PendingDeprecationWarning
                   +-- RuntimeWarning
                   +-- SyntaxWarning
                   +-- UserWarning
                   +-- FutureWarning
                   +-- ImportWarning
                   +-- UnicodeWarning
                   +-- BytesWarning

    Handling Exceptions
        try ... except ... [else ...] [finally ...]       
            A try statement may have more than one except clause. At most one handler will be executed.
            An except clause may name multiple exceptions as a parenthesized tuple. 
                except (RuntimeError, TypeError, NameError):
                    pass
            The last except clause may omit the exception name(s), to serve as a wildcard.
                except:
                    print("Unexpected error:", sys.exc_info()[0])
                    raise
            Clause else is useful for code that must be executed if the try clause does not raise an exception.
           
            A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
           
            A more complicated example having except and finally clauses in the same try statement:
                >>> def divide(x, y):
                ...     try:
                ...         result = x / y
                ...     except ZeroDivisionError:
                ...         print("division by zero!")
                ...     else:
                ...         print("result is", result)
                ...     finally:
                ...         print("executing finally clause")
                ...
                >>> divide(2, 1)
                result is 2
                executing finally clause
                >>> divide(2, 0)
                division by zero!
                executing finally clause
                >>> divide("2", "1")
                executing finally clause
                Traceback (most recent call last):
                  File "<stdin>", line 1, in ?
                  File "<stdin>", line 3, in divide
                TypeError: unsupported operand type(s) for /: 'str' and 'str'


    Raising Exceptions
        raise
            raise NameError('HiThere')

    User-defined Exceptions
        should typically be derived from the Exception class, either directly or indirectly.
       
    Predefined Clean-up Actions
        Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.
            It leaves the file open after this part of the code has finished executing.
                for line in open("myfile.txt"):
                    print(line)
                   
            After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines.     
                with open("myfile.txt") as f:
                    for line in f:
                print(line)


 

原文地址:https://www.cnblogs.com/markjiao/p/1518603.html