Python concise tutorial-learning notes, python concise tutorial
- Double quotation marks and numbers are not included;
- The Delimiter is a comma (,) and cannot be a space.
- Assign values when defining variables.
- Use UTF-8 encoding: #-*-coding: UTF-8-*-or # coding: UTF-8
- String definition: single/double quotation marks
- The % symbol is used to format the string. "% s" indicates to replace the string, "% d" indicates to replace the integer, and "% r" indicates to print out everything.
- Three quotation marks can indicate a multi-line string, which can use single double quotation marks freely
- The escape character is a backslash (\). Note: The backslash at the end of the line indicates that the string is not interrupted in the next line.
- The prefix r or R of the string indicates that the string is a natural string, and the character does not need to be specially processed. The regular expression is processed using the natural string.
- If... elif... elif... else; while loop first defines a True value. When the while True value is True, the loop is executed. When the process ends, the True value is set to False. In the while LOOP, an else clause can be used;... in loop, for loop iteration parameters (I is commonly used) are not defined;
Break termination statement: None of the following break statements will be executed;
The continue statement indicates that the remaining statement of the current block is skipped and the next loop is executed;
- Raw_input (): standard input function; range () returns the number of a sequence. Two parameters indicate the number from the first to the second (the first number does not include the second ), the third parameter indicates the step size.
- Function Definition:
Def function name (parameter ..):
Use global to declare global variables
Default values can be defined for parameters in a function. Parameters with default values must be placed behind parameters without default values.
- Return statements can jump out of the function or return values.
- The pass statement does not do anything. It is generally used as a placeholder statement;
- Document string: ''', starting with an uppercase letter in the first line, ending with a full stop, blank in the second line, and detailed description in the third line; you can use _ doc _ to call the function (double underscores on both sides)
- Module: Named after. py
_ Name _ attribute: determines whether the _ name _ attribute is _ main _.
Module call import module name; module object call: Module name. Object Name
Each. py python program is also a module, which can be called by other programs in the same directory.
- Dir () function: lists the identifiers defined by a module, including functions, classes, and variables.
When you provide a module name for dir (), it returns the name list defined by the module;
If no parameter is provided, it returns the name list defined in the current module.
- Data structure (sequence): list, tuples, and data
List: variable content: x = ['apple', 'bana']
The sort () method is used to sort arrays (for example, list x sorting: x )..sort()】, Sorted to get the sorted copy (for example, to get the copy of list x y: y = sorted (x )]
Append () method: Add a project at the end of the list. For example, add a project rice: x. append ('Rice ') at the end of the x list ')]
Del method: Delete [for example, delete the first item in the x list: del x [0].
Pop () method: Remove from the list and return the Element Object
Insert () method: insert A specified object to the list. For example, add A Project A: x. insert (0, 'A') in the x list ')]
List print by default, a line break is entered. You can add commas (,) at the end of the print statement to replace the line break.
Tuple: The content is unchangeable and is usually used to print the statement: zoo = ('Wolf ', 'elephant ')
To include only one project's tuples, you must add a comma after the project to distinguish it from an object with parentheses.
The tuples can be printed with the % sign;
Dictionary (dict): Key <---> value. The key is unchangeable and the value is variable: dict = {key1: value1, key2: value2}
The item method can be used to capture the key values in the dictionary.
- Sequence: Index operator (capture a specific project, also called subscript operation) and slice operator (capture a part of the sequence, that is, a slice)
The value assignment statement does not create a copy, but just creates a reference (mylist = shoplist), which is equivalent to a shortcut and can be changed all the time;
To copy a list, sequence, or complex object, you must use the slice operation to obtain the copy (mylist = shoplist;
- String method:
Str. startswith ('xx'); 'xx' in str; str. find ('xx ');
Fengefu = '---'
Fengefu. join (str)
- Class and object:
Class/object Methods: There is only one difference from common functions: they must have an additional first parameter name self, which refers to the object itself.
The _ init _ method can be used to initialize objects.
Class variables: shared by all objects of the class.
Object variables: they are owned by each object/instance of the class and do not affect each other.
- Inheritance:
Super class --- inherit ---- subclass;
Class inheritance: When a subclass is defined, the superclass is followed by the tuples. in the class, function inheritance: superclass name. Function Name (self, variable 1, variable x)
Reference: Class Name. function name. variable name (from large to small)
- File)
Specify the file and mode to be opened: f1_file('file.txt ', 'w'), write ('W'), read ('R') <---- the 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 row, including the line break at the end of a row. If the result is null, it indicates the end of the file;
Print ''ends with a comma (,): removes line breaks.
- Memory: pickle module (cpickle), which can be used to store and retrieve any python object
Cpickle. dump (list, f): stores the content in the list to file f;
Stored = cpickle. load (f): extracts the content from f to stored.
- Exception:
Try... try t statement is used to handle exceptions. try-block puts normal statements, and try-block puts error processing statements.
The raise statement can be used to raise an exception and put it in the try-block;
Try... the finally statement is used to process the statements in the finally block no matter whether an exception occurs or not, for example, close ())
- Sys. argv: return the command line parameter. sys. argv [0] indicates the file path of the Code.
Argv [1] [2:] indicates taking the first command line parameter, but removing two bytes. For example, if the command line parameter is "-- help", remove -- and execute the help parameter.
- OS module:
OS. name: 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 in the specified directory. OS. remove (): delete a file; OS. system (): Run shell command; OS. linesep: Specifies 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 (): Check whether the given path is a file or directory; OS. path. existe (): checks whether the given path exists;
- Use the * And ** prefixes to receive tuples and lists. The former stores excess function parameters as a tuple after the * parameter, extra parameters in the latter are considered as Dictionary key/value pairs.
- Lambda: lambda statements (return lambda s: expression) are used to create new function objects and return them at runtime (lambda requires a parameter, only one expression is followed as the function body, and the value of the expression is returned by the new function. Note! : Lambda can only use expressions, even print statements cannot be in the lambda form)
- Exec statement: used to execute python statements stored in strings or files, such as exec 'print "Hello World! "'--- Execute the output Hello World! Statement;
- Eval statement: used to calculate the valid python expression stored in the string, such as: eval ('2 * 3') --- calculate the value of 2*3;
- Assert statement: Used to declare whether a condition statement is true, for example, assert Condition Statement --- determines whether the condition statement is true or not. If the condition statement is false, the assert statement fails, an AssertionError occurs.
- Repr function: used to obtain the standard string representation of an object, for example, repr (I) --- return the standard string representation of list I (reverse quotation marks, it is also called the Escape Character ''to complete the same function, for example, 'I ')