A Concise Python tutorial---learning notes

Source: Internet
Author: User
Tags finally block natural string

    • Characters are enclosed in double quotation marks, and numbers are not enclosed;
    • Delimiter is a comma (,) and cannot be a space
    • Assign a value when the variable is defined
    • With Utf-8 code:#-*-coding:utf-8-*-or #coding:utf-8
    • String definition: Single/double quotes
    • The % symbol is used to format the string, "%s" means replacing it with a string, "%d" represents an integer substitution, and "%r" means that whatever is printed out
    • Triple quotation marks can indicate a multiline string with the freedom to use single and double quotes
    • The escape character is a backslash (\), note: The end of the line backslash indicates that the string continues uninterrupted on the next line
    • String prefixed with R or R indicates that the string is a natural string, where the character does not require special handling, and the regular expression is processed using natural strings
    • if...elif...elif...else; The while loop first defines a true value, while a loop is executed when the truth is false, and the end of the An ELSE clause can be used in the while loop, and thefor...in Loop, the iteration parameter in the For loop (the "I" is often used by the individual) is not defined;
      Break Termination statement: None of the following will be executed;
      The continue statement skips the remaining statement of the current block and executes the next loop;
    • raw_input (): standard input function; Range () returns the number of a sequence, two parameters when the third parameter represents the step from the first to the second (contains the first number does not contain the second), three arguments
    • function definition:
      def function name (parameter ...):
      Declaring global variables with global
      The parameters in the function define default values, and the parameters with default values must be located after the parameters without default values
    • The return statement can jump out of a function or return a value
    • Pass statement does not do anything, generally used as a placeholder statement;
    • Document string:"", beginning of the first line of capital letters, period end, the second line is blank, the third row is described in detail; you can use the __doc__ call (double underline on each side)
    • Module: Named with . py suffix
      __name__ Property: Determines the module performer by determining whether the __name__ property is __main__
      Module call Import module name ; module Object invocation: module name. Object Name
      Each of the. Py Python programs is also a module that can be called by other programs in the same directory
    • dir () function : Lists the identifier of the module definition, including: functions, classes, and variables
      When you provide a module name for Dir (), it returns a list of the name of the module definition;
      If no argument is supplied, it returns a list of names defined in the current module.
    • Data structure (Sequence): list, tuple, data

      List: Content variable: x=[' apple ', ' banana ']
      sort ()The method is used for array sorting "such as List x sort:x.sort(), sorted gets a sorted copy of "If you get a copy of the list X y:y=sorted (x)】
      Append ()Method: Add an item at the end of the list "such as adding a project at the end of the X list rice:x.append (' rice ')】
      delMethod: Delete The first item such as Delete x list:del X[0]】
      pop ()Method: Remove and return the element object from the list
      Insert ()Method: Insert the specified object into the list "as in the X list to start adding an item A:x.insert (0, ' A ')】
      List print default one line break, add a comma (,) to the end of the print statement to replace the line break

      Tuple (tuple): content is immutable and is typically used to print statements:zoo= (' Wolf ', ' Elephant ')
      Include only one item the tuple needs to be followed by a comma to distinguish it from a Parenthesized object
      Tuples can be combined with a% number for printing;

      Dictionary (dict): Key <---> value, key immutable, variable value:Dict={key1:value1,key2:value2}
      ItemMethod can be used to crawl key values in a dictionary
    • Sequence: index operator (grab a specific item, also called subscript operation) and slice operator (grab part of a sequence, i.e. a slice)
      The assignment statement does not create a copy, but creates a reference (Mylist=shoplist), which is equivalent to a shortcut, changing it;
      To implement a copy list or a sequence or complex object, you must use the slice operation to obtain a copy (mylist=shoplist[:]), which is not affected by the modification;
    • String method:
      str.startswith (' xx ');' xx ' in str;str.find (' xx ');

      Fengefu= '---'
      Fengefu.join (str)
    • Classes and objects:
      class/Object methods : There is only one difference from normal functions: they must have an additional first parameter name, Self, which refers to the object itself.
      The __init__ method can be used to initialize an object
      variable of Class : shared by all objects of the class, changed
      variable of object : owned by each object/instance of the class, not affected
    • Inherited:
      Superclass---inherit----subclass;
      class inheritance : When a subclass is defined, a superclass is followed by a tuple, and a function in a class inherits : A superclass name. Function name (self, variable 1, variable x)
      Reference: Class name. Name of the function. Variable name (from large to small)
    • Document class (file)
      Indicate open files and modes:f=file (' file.txt ', ' W '), Mode has write (' W '), read (' R ') <----as default open mode, append (' a ' ) and other modes;
      Write () method :f.write (' xxx '), write; Close () Method:f.close (), close after use;
      The ReadLine () method is used to read an entire line including the line ending newline character, so if the read result is empty, the end of the file is indicated;
      print ' with comma ',' End: Eliminate wrap
    • Memory:Pickle Module (cpickle), which can be used to store and remove any Python object
      cpickle.dump (list,f): Stores the contents of the list in the file F;
      stored=cpickle.load (f): Remove content from f to stored
    • Abnormal:
      The try...except statement is used to handle exceptions, try-the normal statement in the block, and except-the error-handling statement in the block
      The raise statement can be used to throw an exception, placed in a try-block;
      The try...finally statement is used to handle statements in a finally block whether or not an exception occurs, such as closing an operation (Close ())
    • SYS.ARGV: Returns a command-line argument,Sys.argv[0] represents the code itself file path, so the parameter starts from the beginning
      argv[1][2:] means taking the first command-line argument, but removing two bytes, such as the command line argument "--help", remove--, execute the Help parameter
    • OS module:
      os.name: the system platform used;os.getcwd (): Get the current working directory,Os.getenv () and os.putenv (): Read and set environment variables; Os.listdir (): Returns all files and directory names under the specified directory;os.remove (): Deletes a file;Os.system (): Runs the shell command; Os.linesep: String gives the line terminator of the current platform;os.path.split (): Returns the directory name and file name of a path;os.path.isfile () and Os.path.isdir (): Verifies whether the given path is a file or a directory;os.path.existe (): verifies that the given path exists;
    • Use the * and * * prefixes to receive tuples and lists, which store extra function arguments as a tuple after the * parameter, in which the extra arguments are considered to be a dictionary key/value pair.
    • lambda form : Lambda statements (return lambda s: Expressions ) are used to create new function objects and return them at run time (lambda requires a parameter, followed only by a single expression as the body of the function, And the value of the expression is returned by this new function, note! : Lambda can only use expressions, even if the print statement is not in lambda form
    • EXEC Statement : Used to execute Python statements stored in a string or file, such as:exec ' print ' Hello world! ' ---execution output Hello world! Statement
    • eval statement : Used to calculate a valid python expression stored in a string, such as:eval (' 2*3 ')---Calculate the value of 2*3;
    • Assert statement : Used to declare a conditional statement is true, such as:assert conditional Statement---Judge whether the condition statement is true, truth does not return information, the condition statement is false Assert statement failure, A assertionerror error is raised.
    • repr function : Used to get the canonical string representation of an object, such as:repr (i)---Returns the canonical string representation of the list I (the inverse quotation mark, also known as the "translator" can do the same function, such as:' I ')

A concise tutorial for python---learning notes

Related Article

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.