Python Learning Notes

Source: Internet
Author: User
Tags case statement function definition glob print object shallow copy

Python Learning Notes
Python Introduction
Programming
Basic syntax
Variable
Operator
Parameters
Statement control
Function
Data
String
List
Dictionary
Meta-group
Object oriented
Basis
Object Properties
Object methods
Operator overloading
Object inheritance
Advanced Programming
Regular expressions
File processing
XML programming
Network programming
Database
Common standard Libraries
Resources
Python Introduction
    • Python is an explanatory language, and the program is parsed and executed by the interpreter.
    • Version Info: $ python-v
    • Python Case Sensitive
    • Python Help document settings:

      The prerequisite is to install the Python2.5-doc (the name varies depending on the version)

    Env pathondocs=/usr/share/doc/python2.5    # python    >>> help (print)        # # Printing print function information

In Python, you can define a help document for a module or function, using three quotation marks to denote "" ".... "", and then call the function or module of the __doc__ property

    • Test procedure:
    #! env python    print "Hello World"
    • File encoding
    #! Env python    #-*-coding:utf-8-*-
    • Excerpt from some nice sentences:
Program testing can is used to show the presence of bugs, but never to show their absence! ----Edsger W. Dijkstra
Finding a hard bug requires reading, running, ruminating, and sometimes retreating. If you get stuck on one of these activities, try the others.
Basic syntax for programming
  • Comment statements are # represented by
  • Use mathematical formulas to import math modules first
  • Noneis a special value that represents an invalid value, which is different from the one that "None" represents None the value of the string, which has no value.
  • Note == === The difference: The former indicates whether the comparison value is equal in size, and the latter is used to test for the same object.
  • Read user input data:input=raw_input("Please enter a value:")
  • The value read is stored in a string, as shown above input , and if you expect an integer value, the display transformation is required: int(input) .
  • Two Boolean values in Python: True andFalse
  • Determines whether a variable belongs to the specified data type:isinstance(var, type)
  • Long-integer Data representation:2L
  • String:
    • In Python, single and double quotes are exactly the same
    • "" ": indicates that the middle single and double quotes are not resolved, and the string can be wrapped
    • Unicode string to prefix u or u
    • Natural strings are denoted by R prefixes: R "Newlines is indicated by/n"
  • Escape character:
    • /' denotes single quotation mark '
    • /appears at the end of the line, indicating that the string continues on the next line and does not represent a newline
  • Identifier Name:
    • The first letter is uppercase or lowercase letters (a-zA-Z) or"_"
    • Other letters consist of uppercase and lowercase letters (a-zA-Z),"_" and numbers (0-9)
    • Case sensitive
  • Statement:
    • Multiple statements in the same line with ";" Separated
    • A statement is separated by "/" in Multiple lines
  • Indent:

    In Python, you can't indent in a random way. Indenting once represents entering a block, similar to entering the "{}" statement

  • Exec:

    Execute a Python code

  • Eval:

    Calculating expressions

  • Assert:

    Conditional declaration, when fail, throws Assertionerror

  • Null value:

    The null value in Python is None

Variable
    • Variable:

      You do not need to declare and define data types, you can directly use

    • Declaring Global variables:
    Global X
Operator

Special needs to keep in mind: to // divide the integers, return the integer part of the quotient, the rest are the same

    • And and OR operators:

      In Python, the and and OR operators do not return a Boolean value, but instead return the last computed operator, for example:

   ' A ' and ' B ' returns ' B '    a ' or ' B ' returns ' a '
    • There are no ++, -- operators in Python, which take the +=, -= place of implementation functions.
Parameters
    • Like the Java language, Python's parameter passing is a value pass, that is, a copy of the parameter value is passed.
Parameter type
    • Function parameters:

      Multiple parameters are separated by "," after the function, for example:

    lang= ' python '    print ' This was a test for ', Lang
    • printThe statement ends with a comma , representing the branch statement.
    • Default parameters: Only those parameters at the end of the formal parameter list can have default argument values, which means that you cannot declare a parameter with a default value and then declare a formal parameter that has no default value when declaring the function parameter
Parameter passing
    • Data passing on an array or dictionary type is represented by the * and * * prefixes, such as *ARGV, where all parameter passes are stored as array types in the argv variable, and if **argv, stored as key-value pairs in argv.
    • Each command-line argument passed to the program is stored in the SYS.ARGV as a list:

      Sys.argv[0] represents the file name itself, which sys.argv[1]... means that the parameters that are actually passed to the script are passed parameter values for more complex pass-through parameter options, which are implemented with the Gotopt module:

    opts, args = Getopt.getopt (argv, "hg:d", ["Help", "grammar="])
getopt function
    • Receive 3 Parameters: Parameter list (argv), Short flag option (H, G:, D), Long flag option (Help, grammar=)
    • Returns 1 tuple (tuple) opts and a parameter list args:
    OPTs: (flag, argument), flag is the option name, such as-D,--help,argument stores its corresponding parameter value, or none if not    : The remaining parameters, if not, none
    • Short logo Description:
    G: Indicates that the-G  option must be followed by a parameter
    • Long Sign Description:
    Grammar= indicates that the--grammar option must be followed by a parameter

The order of the long and short flag parameters is consistent, allowing a parameter option to be missing, as long as the order is consistent.

Statement control
    • For loop:
For Var in array:
    • Control statements:
      • There is no switch in Python ... case statement, using the If...elif...else statement
      • True and False are called Boolean types. You can interpret them equivalently as values 1 and 0, respectively.
      • The while loop statement can be followed by an ELSE clause
    • Exception statement:
      • Try...except: Catching exceptions
        • Try ... except can follow the Else statement
      • Try...finally: Statements that are always executed when an exception occurs
      • Raise: Throwing an exception
      • Super class: Error and Exception
Function
    • Lambda functions:

      Create a new function object with a lambda operator, for example:

    def base_fun (n):        return lambda s:s*n     //new_fun

Defines a function called base_fun , the result of which the function executes returns a new function new_fun , the argument is, the returned s result is, for example, the function returned is s*n new_fun = base_fun(2) new_fun(s) : s*2 then executes new_fun(5) , then returns5*2=10

    • Glob function:

      Glob uses wildcards to get all the matching files or folders that are stored in the returned list, for example:

    Import glob    Glob.glob ("/home/michael/*/*.mp3")

Get a list of all MP3 files under the "/home/michael" directory and its subdirectories

Data structure string
    • Strings are immutable objects immutable object
    • Common methods:
    Str.upper ()    str.find (CH, [startindex], [endindex])    Str.strip ()
    • Traversal operators in :
In Word:    ...
    • inIt can also be used to determine whether a group contains an element:
    If letter in Word:        ....    If letter isn't in Word: ...        .
    • String module:
String.lowercase: All lowercase letters
List
    • List of references:
      • The assignment statement for the list does not create a copy
      • Copies can be created using the slice of the list
    • Lists are objects that can be changed
    • rangeMethod produces a list of commonly used consecutive numbers
Range (1,5) = [1,2,3,4]range (5) = [1,2,3,4]range (1,5,2) = [1,3]
    • Operator:
+: Connect Multiple list *: Repeat list multiple times
    • List cutting:
t = [' A ', ' B ', ' C ', ' d ', ' e ', ' F ']t[1:3]  = [' B ', ' C ']t[:3]   = [' A ', ' B ', ' C ']t[3:]   = = [' d ', ' e ', ' F ' ]t[:]    = [' A ', ' B ', ' C ', ' d ', ' e ', ' F ']
    • List method:
T1 = [' A ', ' B ', ' c ']t2 = [' d ', ' E ']t1.append (T2): Add list element, parameter can be another list [' A ', ' B ', ' C ', [' d ', ' e ']]t1 = [' A ', ' B ', ' c ']t2 = [' d ', ' E ']t1.extend (t2)  = [' A ', ' B ', ' C ', ' d ', ' e ']
    • string conversion to List
L = List (s) L = s.split () L = s.split (delimiter) #默认的分隔符为空格
    • The list is converted into a string
Delimiter.join (L)
    • List functions
    Li.append (), Li.insert (), Li.extend (), Li.index ()    li.remove (), Li.pop ()
Dictionary
    • Construct: Built-in function dict() creates an empty Dictionary object
    • inoperator to determine if a key value existskey
    • All values are returned:dict.values()
    • getMethod:dict.get(‘key‘, [default])

      Note: In a Dictionary object, only the hashtable object with the method can be a key value, so it must be an immutable object, such as int, float, string, tuple . For example list, dictionary , it cannot be a key.

    • Dictionary-based string formatting:
      • % (key) s denotes value in dictionary that corresponds to the key key value, such as params = {' pwd ': ' Pass ', ' pwd2 ': ' Pass2 '}
    "% (PWD) s is not correct."% params

Returns "Pass is not correct."

    • Dictionary functions
    Del D[index]
    • Locals and Globals:
      • The locals () function returns a copy of the local variable's dictionary
      • The Globals () function returns the dictionary of the actual global variable, and modifying the value in it affects the global variable
Meta-group

Tuple data (tuple) is a non-changing object (immutable), which is typically used to return multiple variable values, for example return firstname, lastname .

    • Tuples can use strings and actions in the list
t = tuple (' abcd ') = = (' A ', ' B ', ' C ', ' d ') t[1:3] =  (' B ', ' C ')
    • Tuple assignments are very flexible, such as swapping two variable values:
A, B = B, a
    • Tuples are useful for returning multiple values:
quot, rem = Divmod (7,3) quot 2rem =  1
    • itemsThe return value of a Dictionary object method is a list of tuples
D = {' A ': 0, ' B ': 1, ' C ': 2}t = D.items ()  =  [(' A ', 0), (' B ', 1), (' C ', 2)]
    • Conversion of tuples to Dictionary objects:
D = dict (t)
    • Tuple data can be a dictionary key to an objectkey
Dic[last, First] = Numberfor, first in dic:    print First, last, Dic[last, first]
    • Tuple functions

Tuple read only, tuple no function method

Object-Oriented Fundamentals
    • Import of packages:

      The package is actually an ordinary directory, that is, the folder, but its characteristics are located in the directory of the __init__.py file; A directory without this file is just a normal folder

    • Self

      Class method is special, you must add the self parameter, equivalent to this in Java, refers to the current object itself

    • Import <module> as <m>:

      The name of the shorthand module in the program

    • Class properties and Data properties:

      Data properties defined in __init__

      Class properties are defined in the class's space, similar to the static data in Java

Object Properties
    • Shallow copy (shallow copy):copy.copy(obj)
    • Deep copy:copy.deepcopy(obj)
    • Determine if an object contains a property:
>>> hasattr (obj, ' attributename ')
    • The property information for the object is stored in one of the objects dictionary :
>>> print p.__dict__{' y ': 4, ' X ': 3}

This example indicates that the object p contains attributes y and x that the values are 4 and 3, respectively.

def print_attributes (obj): for    attr in obj.__dict__:        print attr, getattr (obj, attr)
Object methods
    • Special methods:
      • __INIT__: Initialize the class method, equivalent to the constructor in Java
      • __DEL__: Similar to Java desconstructor, classes are no longer used when they are executed, but cannot be determined when they are run
      • __STR__: The representation of a class object, output when used for print objects, equivalent to the ToString () method in Java
      • __lt__ (self, Other): Returns true for comparisons to other objects, if less than other objects
        • __getitem__ (self, key): After defining this function, you can call its <o>[key] on the object to return the item corresponding to key
        • __len__ (self): Use the built-in Len () function on a sequence object, such as after the __len__ (self) function is defined within an object, you can call the object's Len () function directly
      • __: Python uses __ prefixes to represent private variables, __privatevar, to use _ prefixes to represent variables that are used only within a class or object
    • Repr ():

Returns the canonical string representation of an object, and the effect is the same as the anti-quote ", unlike Str (), where STR () is the output string used in the Print object, repr () and" are returned directly to the string representing the object, and if the two values are the same, the relationship is as follows:

    Print <obj> = = Print Repr (<obj>) = = print ' <obj> '
    • Private methods:

Private methods in Python are denoted by the prefix "__" in front of the method name and cannot be called directly from outside the method

Call private methods can be called by _<class><method> , for example, class test defines a private method called __method() , from the external call is_Test__method

Although it is possible to call private methods this way, it is not recommended to use this method, otherwise it violates the purpose of private methods.

    • The built-in functions of the object:
    Type (), str (), dir () the    dir function returns all properties of the object, field, method    three functions are all attributed to the built-in module __builtin__, so the equivalent of calling __builtin__.type (), __builtin __.str ()

The difference between a function and a method:

    • A function is a procedural statement that refers to a function that belongs to a class object and is defined in a different way.
    • function refers to the pure function, and the class does not have any relationship
    • The first parameter of a method definition must be the class object to which the method belongs, that is, the keyword represents thethis
    • function definition:
Class Time:    ... def print_time (time):    print '%.2d:%.2d:%.2d '% (Time.hour, Time.minute, Time.second)
    • Method definition:
Class time: ...    .    def print_time (self):        print '%.2d:%.2d:%.2d '% (Self.hour, Self.minute, Self.second)
    • Parameters are omitted when the method is called self .
    • __str__(self)Method: Used to print the object information displayed by the object
    • __repr__(self)Method: Used to eval produce results for an object
Operator overloading
    • Overloads + , by defining __add(self, other)__ methods to implement
    • __radd__(self, other)__method is used when the object appears to + the right.
    • When an object implements a __add()__ method, sum() the method applies to the object.
    • __cmp__Used to define the size comparison of objects.
    • When an object implements a __cmp__ method, you can use a sort() method to sort the objects.
Object inheritance
    • Inheritance definition:
Class Hand (Deck): ...    .
High-level programming regular expressions
    • Re.sub
    Import Re    s = ' abcdef '    re.sub (<reg_pattern>, "", s):

The RE module uses the sub method to replace strings that conform to regular expressions, and in order to reduce the effect of "escape character catastrophe" when specifying regular expressions, the R prefix can be added so that all strings in the expression do not need further escaping, such as:

    Re.sub (R '/broad$ ', ' Rd. ', s) is much clearer than re.sub ('//broad$ ', ' Rd. ', s)
    • Re.search (Pattern, ' string ')

      Loosely regular expression: re.search (Pattern, ' string ', re. VERBOSE)

    Pattern = "" "                    ^    # Beginning of string                    m{0,4}    #thousands-0 to 4 M ' s                    $    # End of string" "                    " 
   re.compile (R ' Regpattern '). Search (s)    Re.compile (R ' Regpattern ', re. VERBOSE). Search (s)
File processing
    • Open File:>>> fin=open(‘file.txt‘)
    • Read:
Fin.readline ()
    • Write:
Fin.write (Linetext)
    • Absolute path:os.path.abspath(‘memo.txt‘)
    • Determine if the path exists:os.path.exists(‘memo.txt‘)
    • Get current path:os.getcwd()
    • To determine a file or directory:
Os.path.isfile () Os.path.isdir ()
    • List all Files:os.listdir(cwd)
XML programming parsing XML files
>>> from xml.dom import minidom>>> xmldoc = minidom.parse (filename)

XmlDoc returns an Document object that is a Node subclass of. From Node the inherited methods are: childNodes, firstChild, lastChild, toxml .

Network programming
    • HTTP Status Code
    200-ok    404-not Found    301-Permanent REDIRECT    302-Temporary REDIRECT    304-not modified since last access
Urllib Module
    The Urllib module relies on the Httplib module, which allows you to open the Debug option by setting the Httplib module properties:    httplib. Httpconnection.debuglevel = 1

How to use:

    Urllib.open ()

Use the Minidom.parse function to process various types of files:

    Web page: Urlopen ()    Local file: Open ()    string: Stringio ()

stdout, stderrare file type objects, but can only be 写入 manipulated and cannot be read out. stdinis a read-only file type object.

URLLIB2 Module

Using urllib2 a module to get HTTP resources is done in three steps:

    • Building Request Objects:request = urllib2.Request(res)
    • Build the opener Processor:opener = urllib2.build_opener()
    • Use the built processor to get the Request object:feeddata = opener.open(request)

RequestObject add_header to change the property value of the HTTP header data by method. feeddata.headersis an dictionary object.

Check that the Web service has not updated the different header data used::: Last-Modified If-Modified-Since EtagIf-None-Match

Database ANYDBM Module

anydbmA module stores data as a key-value pair key:value , and can operate as if it were a dictionary data type:

>>> Import anydbm>>> db = Anydbm.open (' dbname.db ', ' C ') >>> db[' keyname '] = ' value of the key ' &G t;>> print db[' KeyName ']

anydbmThe limitation is that the key value must be a string type.

Pickling module

Picklingcan store object data

>>> Import pickle>>> t = [1, 2, 3]>>> pickle.dumps (t) ' (Lp0/ni1/nai2/nai3/na. ') >>> t2 = pickle.loads (t) >>> print t2[1, 2, 3]
Common Standard library Sys
    SYS.ARGV[0] point to program name    sys.version    sys.stdout/sys.stdin/sys.stderr
Os
    Os.name: Platform name, Windows returns "NT", Linux returns "POSIX"    os.getcwd (): Returns the current working directory    os.getenv (), os.putenv (): Read and set current environment variables    Os.listdir (): Returns all files and directories under the specified directory    os.remove (): Delete a file    Os.system (): Execute a shell command    os.linesep: line terminator on the current platform , Linux returns '/N ' under, Windows returns '/r/n '    os.path.split (): Returns a directory name and file name for a path (<dir>,<file>)    Os.path.isfile (), Os.path.isdir (): Verifies whether the given path is a folder or a file    os.path.exists (): verifies that the given path exists

Python Learning Notes

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.