It needs to be noted that the knowledge points will be listed here as a small white role, but if you don’t know much about the information, you won’t do too much research, but first leave an impression

1. Introduction to Python

Python is one of the few programming languages that can claim to be both simple and powerful

Python is simple, easy to learn, free and open, a high-level language, cross-platform, interpretive, object-oriented, extensible, embeddable, and rich in libraries

2. How to install Python

In Windows installation go to https://www.python.org/downloads/ and download the latest version of Python, when the document is the latest version Python 3.6.5. The installation process is the same as that of other Windows software.

If you need to download Linux or Mac, click the system in the red box above and select the corresponding Python version to download.

It took about half an hour to download the software from the official website. In order to save other students’ time, students who need it can click the link below to download it (Windows only) :

Link: https://pan.baidu.com/s/1RHJil0gv4S66jAufOqLdqg password: oogi

After downloading, open the file, and the interface is as follows. There is a small detail to note:

Check the Add Python 3.6 to PATH option (it is not checked by default). After checking this option, you do not need to manually configure environment variables. If you need to change the installation directory, click the Customize Installation option, click Next and enter a custom directory, such as D:\python35, in the installation location.

After the installation is complete, if the following display is displayed, the installation is successful.

Installation success chart

If Python is not installed and you type Python in the command line window, the following error message is displayed:

Install it on Mac OS

For Mac users, you can use Homebrew and install with the brew install python3 command. To verify that the installation is successful, press [Command + Space] (to start Spotlight search), type in Terminal, and press [Enter] to start Terminal. Now, try running python3 to make sure it doesn’t have any errors.

Install it under GNU/Linux

For GNU/Linux users, you can install Python 3 using the distribution’s package manager. For example, on Debian and Ubuntu, you can type: Sudo apt-get update && sudo apt-get install python3. To verify that the installation is successful, you can start the Terminal by opening the Terminal application or by pressing Alt + F2 and typing in gnOMe-Terminal. If this does not work, consult the documentation for the GNU/Linux distribution you are using. Now, run the python3 command to make sure it doesn’t have any errors. You should see Python version information displayed on the screen after running the command:

$python3 -v Python 3.6.5Copy the code


3. First project and compiler selection

At the command line, type Python to the interpreter prompt, and then print(” Hello world”)

How do I exit the interpreter prompt? Just type exit()

Python3. X print requires parentheses, while 2.X does not

Pycharm (pycharm) – Pycharm (pycharm) -pycharm (Pycharm) http://www.jetbrains.com/pycharm/download/#section=windows or baidu can also be downloaded installation can find, not too special points, all can by default; After installation, click open ~

After installing the first Project, open PyCharm and the interface shown in Figure 1 will be displayed. Click “Create New Project” and a selection box will pop up to select the path of the Project, which can be modified by default

After creating the project, right click on the project and select NEW, you will find that you can create a lot of things, such as directories, files, package, etc. In this case, you can select Python File, and you will be asked to fill in the name of the File, so you can customize the input here, jb_helloWorld, Click OK, print(“jb_hello_world”), right-click the file, select RUN file, and you will see the contents of print below. Congratulations, the first project is complete. But remember, to create a File in the future, right click on the corresponding project ->New->Python File-> enter the filename to create it

Executing the Python file in the command line window just created a file using PyCharm. How does this file work without PyCharm? This is usually done in a command line window by typing the absolute path of the corresponding Python file, such as python D:\jbtest\jb_helloworld.py, to see the output of the file in the command line window

Summary: You should know how to write and open Python programs, so let’s learn more about the basics

4. The Python

A comment is any copy that exists to the right of the # to provide information to the reader; Here’s an example:

Print ("jbtest") #print is a functionCopy the code

While # is used for single-line comments, triple quotes are used for multi-line comments, as follows:

This is a multi-line comment.Copy the code

2) Literal constants such as numbers 1, 2, 334, or text such as This is a string, are literal constants, with the characteristic that the value cannot be changed; (floats) Numbers are of two types: integers and floats. For example, 2 is an integer and 2.123 is a floats. A string is a string of words, such as ‘This is JBtest! ‘5) Single quotes Single quotes are used to specify strings, such as ‘This is JBtest! ‘All contents inside quotation marks are preserved, such as Spaces and symbols. 6) Double-quoted strings work the same way as single-quoted strings, for example, ‘This is JBtest! ‘and “This is JBtest! It’s the same thing; 7) Triple quotation marks (“”” “or “”) are used for multi-line comments as follows:

This is a multi-line string, this is the first line of it. This is second line. "What is your name? ," he asked. 'My name is jb'. '''Copy the code

Note that the triple quotation marks are free to use single and double quotation marks

8) Strings are immutable Remember that strings, once created, cannot be changed. There are two common formatting methods, such as percent method and format method. Percent sign method:

Print (" my name is %s and %d is old "% (" JB ", 2))Copy the code

Format method — Normal use:

Print (" format("jb", 2)") print(" format("jb", 2)") print(" format("jb", 2Copy the code

The format method changes the formatting order by filling in the numbers in parentheses:

Format ("jb", 2) print(" {1}, {0}} ". Format ("jb", 2)) print(" {1}, {0}"Copy the code

Format method — fetch variables by key:

Format (name="jb", age=2) print(" name= {name}, age=2) print(" name= {name}, age=2) print(" name= {name}, age=2Copy the code

What do I do when I need a multi-line string? In addition to the triple quotation marks mentioned above, you can use the new line \n escape sequence ~

This is first line \n This is second line.
Copy the code

In this case, \n means newline, and more information about escaped characters is as follows:

Escape character role
End-of-line \ Line continuation operator
\a Ring the bell
\ 000 empty
\t Horizontal tabs
\o Octal numbers represent characters
\ \ The backslash
\b backspace
\n A newline
\r enter
\x Hexadecimal numbers represent characters
\ ‘ Single quotes
\e escape
\v Vertical TAB character
\f Change the page

If you need to specify some unprocessed string, such as an escape sequence, you need to prefix the string with r or r to specify a Raw string.

r"Newlines ar indicated by \n"
Copy the code

Tips: Use the original string throughout the regular expression process, otherwise there will be a lot of Backwhacking to deal with. 12) Variables because constants are immutable, they can’t satisfy more needs, so variables are born. Variables can store anything, so they need to be named. 13) Identifiers Named variables are an example of an identifier. Identifiers are given names for something. When you name identifiers, you need to follow the following rules: The first character must be a letter of the alphabet (uppercase ASCII character or lowercase ASCII character or Unicode character) or an underscore (_).

Other parts of the identifier can consist of characters (uppercase ASCII characters, lowercase ASCII characters, or Unicode characters), underscores (_), and digits (0 to 9).

Identifier names are case sensitive. For example, myName and myname are not identical. Notice that the former is lowercase n and the latter is uppercase N.

The value contains letters, digits, and underscores (_) and must start with a letter or underscore (_). Python is case-sensitive and case-sensitive;

Attached is a naming rule found on the Internet:

1. Project name: capitalize the first letter and use underscores to increase readability, such as Ui_test; 2. Package name and module name: all lowercase letters; 3. Class name: uppercase, lower case, multiple words camel name; 4. Method (function) name: all lowercase, multiple words separated by underscores; 5. Parameter name: lowercase word. If it conflicts with keywords, underline the parameter name, such as _print. 6. Variables: Lowercase, separate multiple words with underscores; 7. Constants: All caps, separate words with underscoresCopy the code

14) There are 6 data types, including number, string, list, tuple, set and dictionary; Immutable data: Number (Number), String (String), Tuple (Tuple), and Sets (set); Mutable data (two) : List, Dictionary. Python refers to anything in a program as an Object. Python is Strongly object-oriented because everything is an object, including numbers, strings, and functions. 16) Logical and physical Lines Physical lines are what you see when you write a program. A logical line is a single statement that Python sees. Python assumes that there is a logical line for every physical line.

Print I = I + 5; print 5; This example has three physical rows and four logical rows 2 I = I + 5; print 5; This example has one physical row and two logical rowsCopy the code

Here is a tip, in Python, it is recommended that one physical line corresponds to one logical line, and use semicolon ~ 17 as little as possible) indentation in Python is very very important!! Wrong indentation can lead to a lot of devious ways, so don’t use Notepad to write code! Use a professional IDE! Statements placed together must have the same indentation, for example:

Print (I) print(I +1) print(I +1) print(I +1) The File "E: / PyCharm Community Edition 2017.2.1 PycharmProjecst/jbtest/jbtest1 py", line 2 print (I) ^ IndentationError: Unexpected indent # Indent error: Unexpected indentationCopy the code

So how do you avoid unnecessary problems with indentation? The official recommendation is to use 4 Spaces for indentation, and good editors will do this automatically without any manipulation, or use the TAB key

18) Operators Operators are functions that perform certain operations and can be expressed by symbols such as + or special keywords;

Here's a quick overview of the available operators: + (plus) adds two objects. 3+5 produces 8. 'a' + 'b' prints 'ab'. - (subtraction) Subtracts another number from one, assuming zero if the first operand does not exist. -5.2 will print a negative number. 50-24 will print 26. * (multiply) gives the product of two numbers, or returns the result of repeating the string a specified number of times. 2 times 3, output 6. 'la' * 3, output 'lalala'. ** (power) returns x to the y power. 3 **, output 81 (that is, 3 * 3 * 3 * 3). / (divided by) x divided by y 13/3, output 4.3333333333333. // (divisible) x divided by y and rounded down to the nearest integer. 13 over 3, output 4. Minus 13 over 3, output minus 5. % (mod) returns the remainder of the division operation. 13%3, output 1. -25.5% 2.25, output 1.5. << (left shift) Moves the digit's bit to the left by the specified number of digits. (Each number is represented in memory as a binary number, that is, 0 and 1.) 2 << 2 outputs 8. 2 is written in binary as 10. Moving two bits to the left gives you 1000, which represents the decimal 8. >> (Right shift) Moves the digit's bit to the right by the specified number of digits. 11 >> 1, output 5. 11 is represented as 1011 in binary. Move one bit to the right and type 101. This result represents 5 in decimal. & (bitwise and) Bitwise and manipulation of numbers. 5 &3, output 1. | (or) for the bitwise or operator number. Output 5 | 3, 7. ^ (bitwise xor) Perform bitwise xor operations on numbers. 5 to the third, output 6. The inverse bitwise of x is -(x+1). ~5 outputs -6. < (less than) returns whether x is less than y. All comparison operators return True or False. Note the capital letters in these names. 5 < 3, print False, 3 < 6, print True. Comparisons can be arbitrarily formed into links: 3 < 5 < 7, which returns True. > (greater than) returns whether x is greater than y. 5 > 3 returns True. If both operands are numbers, they are first converted to a common type. Otherwise, it will always return False. <= (less than or equal to) returns whether x is less than or equal to y. x = 3; y = 6; X <=y returns True. >= (greater than or equal to) returns whether x is greater than or equal to y. x = 4; y = 3; X >=3 returns True. == (equal) Compares whether two objects are equal. x = 2; y = 2; X == y, return True. x = 'str'; y = 'stR'; X == y, return False. x = 'str'; y = 'str'; X == y, return True. ! = (not equal) Compares whether two objects are not equal. x = 2; y = 3; x ! = y, returns True. Not (Boolean "not") Returns False if x is True. Return True if x is False. x = True; Not x, return False. And (Boolean "and") x and y returns False if x is False, otherwise y evaluates. When x is False, x = False; y = True; X and y will return False. In this case, Python will not evaluate y because it already knows that the left side of the and expression is False, which means that the entire expression will be False and nothing else. Or (Boolean "or") returns True if x is True, otherwise it returns the computed value of y. x = Ture; y = False; X or y will return true.Copy the code

In a given expression, Python evaluates the next highest-priority operator and expression in the table first.

priority Escape character role
1 lambda Lambda expressions
2 if – else Conditional expression
3 or Boolean or
4 and Boolean and
5 not x Boolean “not”
6 in, not in Members of the test
7 is, is not Uniformity test
8 <, <=, >, >=, !=, == To compare
9 | Bitwise or
10 ^ The bitwise exclusive or
11 & Bitwise and
12 < < > > mobile
13 The +, – Add and subtract
14 *, /, / /, % Multiply, divide, divide, and mod
15 +x, -x, ~x Positive, negative, and bitwise negative
16 ** exponentiation
17 x.attribute Attribute reference
18 x[index] The subscript
19 x[index:index] Addressing section
20 x(arguments…) A function call
21 (expressions…) Binding or tuple display
22 [expressions…] The list shows
23 {key: value… } The dictionary shows
24 {expressions… } String conversion

In addition to making expressions easier to understand, parentheses can also change the order in which expressions are evaluated;

2 plus 3 times 4, multiply first and then add. 2 plus 3 times 4, add first and then multiplyCopy the code

21) Control flow situations like: Do you need the program to make some decisions and do different things depending on the situation, such as printing ‘Good Morning’, ‘Good Morning’ or ‘Good Evening’ or ‘Good Evening’ depending on the time of day? Control flow is needed to change the order of work. There are three types of control flow statements in Python — if, for, and while.

The if statement checks conditions: if the condition is True, we run a statement (called if-block or if block), otherwise we run another statement (called else block or else block). The else clause is optional.

Int_score = int(input(" please input your score ")) #input = int(input(" please input your score ")) Print (" optimal ") < = 80 elif int_score < = 90: print (" good ") < = 60 elif int_score < 80: print (" ") else: if int_score < 60: Print (" difference ") Print result: Please enter your score: 20 differenceCopy the code

The elif statement merges two connected if elif-if else statements into an if-elif-else statement. This makes the process much simpler.

If you hit a condition inside an if, but you don’t want to process it internally, you can just type pass. Pass is an empty statement that doesn’t do anything. A while statement can also have an else clause as an optional option.

i = 8; while i < 10: print(i); i = i + 1; else: print("end of while"); Output: 8 9 end of whileCopy the code

Note: There are two ways to break a while/for loop: break and continue~ The IN statement is another type of looping statement that iterates over a series of objects, meaning that each item in the sequence is iterated over.

Print (I) else: print('The for loop is over') 1 2 3 4 The for loop is overCopy the code

A break statement is used to break a loop, that is, to terminate the loop. Else blocks will not execute.

For letter in 'Python': # first instance if letter == 'h': break print(' letter :', letterCopy the code

The continue statement tells Python to skip the rest of the current loop block and continue with the next iteration of the loop;

For letter in 'Python': if letter == 'h': continue print(' letter :', letter) O Current letter: nCopy the code

A function is a reusable piece of program that allows you to give a name to a code block. It allows you to run a block of code anywhere in your program with that particular name and repeat it as many times as you want. The above study also used a number of built-in functions, such as Len and range. Functions can be defined by the keyword def. This keyword is followed by the identifier name of a function, followed by a pair of parentheses, which can include the names of some variables, and terminated with a colon to close the line.

Def say_hello(): print('hello world') # say_hello() # call the function output: hello worldCopy the code

Function parameters Parameters in a function are specified by placing them in a pair of parentheses used to define the function, separated by commas. The names given when you define a function are called parameters, and the values you supply to the function when you call it are called arguments.

def print_max(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: Print (b, 'is maximum') print_max(3, 4) x = 5 y = 7 print(b, 'is maximum')  4 is maximum 7 is maximumCopy the code

29) Local variables When you declare variables in the definition of a function, they do not in any way relate to variables that are outside the function but have the same name. That is, these variable names only exist in the part of the function. This is called the scope of a variable. The scope of all variables is the block in which they are defined, starting at the definition point where their names are defined.

x = 50 def func(x): Print ('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is', x)  x is 50 Changed local x to 2 x is still 50Copy the code

If you want to assign a value to a variable at the top level of the program, and it is not affected by other scopes, you can use global to tell the program that it is a global variable.

x = 50 def func(x): Global x print('x is', x) print('Changed local x to', x) func(x) print('x is still', x)  x is 50 Changed local x to 2 x is still 2Copy the code

31) Default parameter values For some functions, you may want to make some parameters optional and use default values to avoid situations where the user does not want to provide them with values. Default parameter values can help to resolve this situation.

Def say (message, times = 1) : print (message * times) say, 'Hello,' say, 'World', 5) of the output results: Hello WorldWorldWorldWorldWorldCopy the code

If you have many functions and you want to specify only some of them, you can assign values to them by naming them. This is the advantage of keyword arguments: functions are easier to use without worrying about the order of arguments. You can assign values only to parameters that you want to assign, as long as all the other parameters have default values.

def func(a,b=5,c=10): Print ('a is ',a,' and b is ',b,' and c IC ',c) func(3,7) func(25,c=24) func(c=50,a=100)  a is 3 and b is 7 and c ic 10 a is 25 and b is 5 and c ic 24 a is 100 and b is 5 and c ic 50Copy the code

33) Variable parameter variable parameter is the number of parameters passed is variable, can be 1, 2 to any, or can be 0; In Python, arguments with * are used to accept a variable number of arguments.

def funcD(a, b, *c): print(a) print(b) print("length of c is: %d "% len(c)) print(c) funcD(1,2,3,4,5,6,7,8,9)Copy the code

The first two arguments are accepted by A and B, and the remaining seven arguments are accepted by C, which in this case is a tuple. When funcD is called, it must pass at least two arguments, all of which are put into C. If there are only two arguments, then C is an empty tuple.

If the last parameter in a function definition is prefixed with ** (double star), all other keyword arguments other than the normal parameter are passed to the function in a dictionary

Def func(a,**b): print(a) for x in b: print(x+':'+ STR (b[x])) func(100,c=' hello ',b=200) def func(a,**b): print(a) for x in b: print(x+':'+ STR (b[x])) func(100,c=' hello ',b=200Copy the code

B is a dict object instance that takes keyword arguments B and c. 34)return statements Return statements are used to return from functions, that is, interrupt functions. We can also choose to return a value from the function when we interrupt it.

Def maximum(x,y): if x>y: return x elif x == y: return 'The numbers are equal' else: return y print(Max (2,3)Copy the code

Python has a wonderful feature called DocStrings, which are often referred to as DocStrings for short. DocStrings is an important tool and should be used as much as possible because it helps make your program documentation easier to understand. You can even recover the docstring from a function while the program is running!

Def print_max(x,y): "" prints the largest number of two numeric values. X = int(x) y = int(y) if x > y: print(x,'is maximum') else: Print (y,'is maximum') print_max(3,5) print(print_max.__doc__) Both of these numbers should be integersCopy the code

The Python module, which is a Python file ending in.py, contains Python object definitions and Python statements. Modules allow you to organize your Python code blocks logically. Grouping related code into a module makes your code easier to use and understand. Modules can define functions, classes, and variables. Modules can also contain executable code.

Def print_func(par): print "Hello: ", par returnCopy the code

37) After the import statement block is defined, we can use the import statement to import modules. The syntax is as follows:

import module1[, module2[,... moduleN]
Copy the code

For example, to reference the module Math, you can import Math at the very beginning of the file.

Support. Print_func ("Runoob") : Hello: RunoobCopy the code

38)from.. Python’s FROM statement lets you import a specified part of a module into the current namespace. The syntax is as follows:

from modname import name1[, name2[, ... nameN]]
Copy the code

For example, to import the Fibonacci function of the module FIB, use the following statement:

from fib import fibonacci
Copy the code

This declaration does not import the entire FIB module into the current namespace; it only imports Fibonacci in fib individually into the global symbol table of the module that executes the declaration. Each module has a name, and statements in modules can find the name of the module they are in. This is useful for the specific purpose of determining whether a module is running on its own or imported to run.

if __name__ == '__main__': print('This program is being run by itself') else: Print ('I am being imported from another module')  $ python module_using_name.py This program is being run by itself $ python >>> import module_using_name I am being imported from another moduleCopy the code

A package is a folder that contains modules with a special init.py file. Packages are a convenient way to organize modules hierarchically. The built-in dir function in Python is used to display identifiers defined in modules, including functions, variables, classes, etc. The dir() function can take arguments to modules, classes, functions, and so on

The dir() function, with no arguments, returns a list of variables, methods, and types defined in the current range;

Returns a list of attributes and methods for a parameter. If the argument contains the method __dir__(), that method will be called.

>>> dir(sys) ['__displayhook__', '__doc__','argv', 'builtin_module_names','version', 'version_info] # here only show part of the item # given the current module attribute name > > > dir () [' __builtins__', '__doc__', '__name__', '__package__', 'sys]Copy the code

42) Data Structure A data structure is a structure that aggregates data together. In other words, they are collections that store a series of related data. There are four built-in data structures in Python — lists, tuples, dictionaries, and sets.

43) Lists LISTS are collections that hold a series of ordered items that can be modified, whereas strings and tuples cannot

Here are some ways to use lists:

methods describe
list.append(x) Add an element to the end of the list equivalent to a[len(a):] = [x]
list.extend(L) Expands the list by adding all elements of the specified list, equivalent to a[len(a):] = L
list.insert(i, x) Inserts an element at the specified position. The first argument is the index of the element to be inserted in front of it. For example, a.insert(0, x) will be inserted before the entire list, and a.insert(len(a), x) equals a.append(x).
list.remove(x) Removes the first element in the list whose value is x. If there is no such element, an error is returned
list.pop([i]) Removes an element from the specified position in the list and returns it. If no index is specified, a.pop() returns the last element. The element is then deleted from the list
list.clear() Remove all items from the list, equal to del a[:]
list.index(x) Returns the index of the first element in the list whose value is x. An error is returned if there are no matching elements
list.count(x) Returns the number of occurrences of x in the list
list.sort() Sort the elements in the list
list.reverse() Invert the elements in the list
list.copy() Returns a shallow copy of the list, equal to a[:]

44) A quick list of objects and classes is using instances of objects and classes. When you enable a variable I and assign the integer 5 to it, you can think of creating an object (instance) I under the int class (type).

Tuples are used to store multiple objects together. One feature of tuples, like strings, is that they are immutable, that is, you cannot edit or change a tuple.

>>> t = 12345, 54321, 'hello! ' >>> t[0] 12345 >>> t (12345, 54321, 'hello! ') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello! '), (1, 2, 3, 4, 5))Copy the code

Tuples are always output with parentheses to express nested structures correctly.

Tuples are defined by specifying items in parentheses, separated by commas. Tuples are often used to ensure that a statement or user-defined function can safely take a set of values, meaning that the values within a tuple do not change.

46) Dictionaries Dictionaries are indexed by keywords, which can be of any immutable type, usually strings or values. The best way to think of a dictionary is as an unordered set of key => value pairs. Keywords must be different within the same dictionary. A pair of braces creates an empty dictionary: {}.

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
Copy the code

The dict() constructor builds the dictionary directly from the list of key-value pairs. If there is a fixed schema, the list derivation specifies a particular key-value pair:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
Copy the code

The main functions of sequences are qualification tests (that is, in and not in expressions) and index operations that allow us to directly retrieve specific items in the sequence

Set A set is an unordered set of non-repeating elements. Basic features include relationship testing and elimination of duplicate elements. You can create collections with curly braces ({}). Note: To create an empty collection, you must use set() instead of {}; The latter creates an empty dictionary, a data structure we’ll cover in the next section. Here’s a simple demo:

> > > basket = {' apple ', 'orange', 'apple', 'pear', 'orange', 'banana'} > > > print (basket) # remove duplicate {' orange ', 'banana', 'PEAR ', 'apple'} >>> 'orange' in basket # Check members True >>> 'crabgrass' in basket False >>> # The following illustrates the operation of two sets... > > > a = set (' abracadabra ') > > > b = set (' alacazam ') > > > only one letter in a # a {' a ', 'r', 'b', 'c', 'd'} > > > a - b # in a letter, But not in b {' r ', 'd', 'b'} > > > a | b {# a or b in the letters' a ', 'c', 'r', 'd', 'b', 'm' and 'z', 'l'} > > > a & b # in a and b are some letter {' a ', 'c'} > > > a ^ b # letters in a or b, but not at the same time in a and b {' r ', 'd', 'b', 'm' and 'z', 'l'}Copy the code

49) Object-oriented Programming Of all programs written to date, programs have been designed around functions, that is, blocks of code that can process data. This is called procedural programming. Classes and objects are two main aspects of object-oriented programming.

Introduction to the describe
class A collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
Class variables Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are not usually used as instance variables.
Data members Class variables, or instance variables, are used to process data related to a class and its instance objects.
Methods to rewrite If a method inherited from a parent class does not meet the needs of a subclass, it can be overridden, a process called method override, also known as method rewriting.
The instance variables Variables defined in a method apply only to the class of the current instance.
inheritance A derived class inherits the fields and methods of a base class. Inheritance also allows an object of a derived class to be treated as a base class object.
instantiation Create an instance of a class, a concrete object of the class.
methods A function defined in a class.
object Instance of a data structure defined by a class. An object consists of two data members (class variables and instance variables) and methods.

50) Methods of the self class differ from ordinary functions in only one particular way — they must have an extra first argument name, which by convention is self. Self represents an instance of the class and represents the address of the current object, while self.class refers to the class. Self is not a Python keyword.

Class uses the class statement to create a new class, followed by the name of the class and terminated with a colon:

P = Person() print(p)Copy the code

52) Method classes and objects can have methods just like functions, except that we have an additional self variable.

class Person: def say_hi(self): print('Hello, how are you? ') p = Person() p.say_hi()Copy the code

The __init__ method is run as soon as the class’s object is instantiated. This method initializes any target object that you want to operate on. Here you have to notice the double underscore around init.

class Person:
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is', self.name)
p = Person('Swaroop')
p.say_hi()
Copy the code

There are two types of fields — class variables and object variables. Class variables are common throughout the instantiated object. The

55) Inheritance One of the main benefits of object-oriented programming is code reuse, and one way to achieve this reuse is through inheritance mechanisms. Inheritance can be understood as type and subtype relationships between classes. Class Derived class name (base class name) : //… The base class name is written in parentheses, and the base class is specified in the tuple when the class is defined. Some features of inheritance in Python: 1: The base class’s construct (__init__() method) is not called automatically in inheritance, it needs to be specifically called in the construct of its derived class itself. 2: When calling a method of a base class, prefix the base class name with the self parameter variable. The difference is that ordinary functions called from classes do not require the self argument 3: Python always looks for methods of the corresponding type first, and if it cannot find a method in a derived class, it starts looking in the base class one by one. (First look for the method called in this class. If not, look in the base class.) If more than one class is listed in an inheritance tuple, it is called “multiple inheritance”.

#! /usr/bin/python # -*- coding: utf-8 -*- class Parent: Def parentMethod(self): print(self, attr) def setAttr(self, attr): ParentAttr = attr def getAttr(self): print(" paren.parentattr :", paren.parentattr) class Child(Parent): Def __init__(self): print(" call constructor ") def childMethod(self): Print (' call the subclass method ') c = Child() # instantiate the subclass c.child method () # call the subclass method c.parent method () # call the parent method c.setattr (200) # call the parent method - Set attribute value c.getattr () # Call the method of the parent class again - get the result of the attribute value output: call the subclass constructor method call the subclass method call the parent class method parent class attribute: 200Copy the code

56) Input and Output If you want to get the user’s input and print out some returned results to the user, you can use the input() function and print function respectively to achieve this requirement. For input, you can also use various methods of the STR (String, String) class. Another common input/output type is processing files. Creating, reading, and writing files are essential functions for many programs.

57) User input

Def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input("Enter text: ") if is_palindrome(something): Print ("Yes, it is a palindrome") else: print("No, it is not a palindrome") jbj Yes, it is a palindromeCopy the code

58) Files can be opened or used and read or written to by creating an object belonging to the File class and using its read, readline, and write methods appropriately. When you are done with the file, you can call the close method to tell Python that you are done with the file.

jb = "if you make your work also fun: Use python~" # open file edit f = open("jb.txt",'w') # Write text to the file. F = open("jb.txt") while True: line = f.readLine () # if len(line) == 0: Break print(line,end= ") f.close() if you make your work also fun: use python~Copy the code

The open modes can be read mode (‘r’), write mode (‘ W ‘), and append mode (‘a’) 59. Pickle2 Python provides a standard module called Pickle, with which you can store any pure Python object into a file and retrieve it later. Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle Pickle

Import pickle JB = 'jb' jblist = ['apple','mango',' Carrot '] f = open(JB,' WB ') F. close() del jblist f = open(jb,'rb') # print(storedList)  ['apple', 'mango', 'carrot']Copy the code

When we read or write a file or when we want to communicate with other computers on the Internet, we need to convert our Unicode strings into a format that can be sent and received, called “UTF-8”.

#	encoding=utf-8 import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text)
Copy the code

61) Exception When I want to read a file, but the file does not exist, what to do? Or accidentally deleted during the execution of the program, how to do? These are handled by using exceptions. Imagine a simple print function call. What happens if you misspell print as print? You’ll notice that it starts with a capital letter. In this case, Python raises a syntax error.

>>>	Print("Hello World") Traceback (most recent call last):
File "<stdin>", line 1, in <module> NameError: name 'Print' is not defined
>>>	print("Hello World")
Hello World
Copy the code

You will notice that a NameError is thrown, and Python will print out where the detected error occurred. This is what an error handler does for this error.

63) Exceptions can be handled by using a try.. Except to handle exceptions. You typically place the usual statements in the try block and the error handler code in the except block.

try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me? ') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {}'.format(text))Copy the code

An exception can be Thrown using the raise statement by providing the name of the error or exception and the object on which the exception is Thrown. The error or Exception that can be thrown must be a direct or indirect descendant of the Exception class.

import traceback def throw_error(): Print ("jb") throw_error() Traceback (most recent call last): The File "E: / PyCharm Community Edition 2017.2.1 PycharmProjecst/jbtest/jbtest1 py", line 9, In < module > throw_error () the File "E: / PyCharm Community Edition 2017.2.1 PycharmProjecst/jbtest/jbtest1 py", line 5, In throw_error raise Exception(" raise an Exception ") # print cannot execute Exception: raise an ExceptionCopy the code

65)Try … Finally assumes that a file is being read. How do YOU ensure that file objects are closed correctly, regardless of whether an exception occurs? This can be done with a finally block.

Import sys import time f = None try: f = open("poem.txt") # line = f.readline() if len(line) == 0: Break print(line, end= ") sys.stdout.flush() print("Press CTRL +c now") # print("Could not find file poem.txt") except KeyboardInterrupt: print("!! You cancelled the reading from the file.") finally: if f: f.close() print("(Cleaning up: Closed the file)")Copy the code

The with statement cleans up the current object regardless of any errors in the with code.

with open("jb.txt") as f:
for line in f:
    print(line, end='')
Copy the code

The Python standard library contains a large number of useful modules and is part of every standard Python installation package. Familiarity with the Python standard library is important, because many problems can be easily solved if you know what those libraries can do.

The SYS module includes a very useful set of services containing many function methods and variables for handling Python runtime configurations and resources;

function describe
sys.argv The command line argument List, the first element is the program’s own path
sys.modules.keys() Returns a list of all modules that have been imported
sys.exc_info() Gets details about the exception classes exc_type, EXC_value, and ext_traceback that are currently being processed
sys.exit(n) Exit program, normal exit exit(0)
sys.hexversion Gets the version value of the Python interpreter in hexadecimal format, such as 0x020403F0
sys.version Gets the version information for the Python interpreter
sys.maxint Maximum Int value
sys.maxunicode The maximum Unicode value
sys.modules Returns the module field imported by the system. Key is the module name and value is the module
sys.path Returns the search path for the module, initialized using the value of the Pythonpath environment variable
sys.platform The operating system platform name is displayed
sys.stdout The standard output
sys.stdin The standard input
sys.stderr Error output
sys.exc_clear() Used to clear current or recent error messages from the current thread
sys.exec_prefix Returns the location where the platform-independent Python files are installed
sys.byteorder Local byte rule indicator, ‘big’ for big-endian platform, ‘little’ for little-Endian platform
sys.copyrighte Document Python copyright-related things
sys.api_version C API version of the interpreter
sys.getdefaultencoding() Returns the default character encoding currently used
sys.getfilesystemencoding() Returns the name of the encoding that converts Unicode file names to system file names
sys.setdefaultencoding(name) Used to set the current default character encoding
sys.builtin_module_names List of modules imported by the Python interpreter
sys.executable Python interpreter path
sys.getwindowsversion() Get the Windows version
sys.stdin.readline() Read a line from standard input,
sys.stdout.write(“a”) Screen output A

69) What should the logging module do if it wants to store some debugging information or important information somewhere so that it can check whether the program is working as expected? How should this information be “stored somewhere”? This can be done through the logging module.

import logging logging.debug('This is debug message') logging.info('This is info message') logging.warning('This is Warning message') warning :root:This is warning messageCopy the code

70) Passing tuples It takes only one tuple to return two different values from a function

def get_error_details(): Return (2, 'details') errnum, errstr = get_error_details() print(errnum) Print (errstrCopy the code

The fastest way to swap two variables in Python is

a=5; Print (a) print(b) print(b) print(bCopy the code

71) Special method

methods describe
__init__(self, …) This method is called when the newly created object is returned ready for use
__del__(self) This method is called before the object is deleted (its timing is unpredictable, so avoid using it)
__str__(self) This is called when we use print or when STR () is used
__lt__(self, other) Called when the less than operator (<) is used. Similarly, special methods are called when using all other operators (+, >, and so on)
__getitem__(self, key) Called when an index operation uses x[key]
__len__(self) Called when the built-in len() function is used on a sequence object

If a statement block contains only a single statement, it can be specified on the same line

flag = True
if flag: print('Yes')
Copy the code

The Lambda statement can create a new function object that is an anonymous function; Essentially, a lambda takes an argument followed by an expression as the body of the function, and the value that the expression executes is the return value of the new function.

G = lambda x: x ** 2 print g(3Copy the code

74) List derivation List derivation is used to derive a new list from an existing list; Example: Now that you have a list of numbers, you want a list of numbers that will be multiplied by 2 if they are greater than 2. List derivation is ideal for such cases.

Print (listTwo = [2* I for I in listOne if I > 2] print(listTwo)Copy the code

The assert statement is ideal for asserting that something is true. For example, you are very sure that a list you are using contains at least one element, and you want to make sure that it is true, and then throw an error if it is not true. An AssertionError is thrown when a statement assertion fails.

Mylist = ['item'] assert len(myList) >= 1 mylist.pop() assert len(myList) >= 1  Traceback (most recent call last): File "C:/Users/jb/PycharmProjects/jbtestprojects/testplay.py", line 4, in <module> assert len(mylist) >= 1 AssertionErrorCopy the code

Decorators are shortcuts to applying wrapping functions. For example:

def cal(x, y):
    result = x + y
    return result
Copy the code

I have a function here, and if I have N of these functions, if I want to do a Log operation on each function, it looks like this

    def cal(x, y):
        logging.info("111")
        result = x + y
        return result
        
    def cal1(x, y):
        logging.info("2222")
        result = x + y
        return result
Copy the code

If you have N functions, add a print() to each of them, and then delete them manually when you don’t need them.

def log(func):
    def wrapper(*arg,**kw):
        logging.warn("%s " % func.__name__)
        return
    return wrapper()

@log
def cal(x, y):
    result = x + y
    return result
    
@log
def cal1(x, y):
    result = x + y
    return result  
Copy the code

From now on, you just need to type the @ function name before execution, and that’s about it

77) Tips In the process of using Python, you need to use a variety of third-party libraries, before the creation of each manual installation, a variety of environments (Windows/Linux), such as pain! But there’s a twist

Pycharm allows you to quickly install all the libraries you need without having to install them yourself. File->Settings>Projects Interpreter – click on the + sign to enter the desired library and click Install.

Conclusion after another, spent more than two weeks time to finish the book on sort out and then go back and look back, feel is more suitable for novice to read, speak the point is not particularly deep, also not too detailed, of course, can only leave the impression that is certainly to understand ~ but, behind the notes about the order of this book is very mess, so also follow together disorderly… Skip reading.

The follow-up plan will follow the previous plan. Next, I will read the stupid methodology Python, Liao Xuefeng 3.0 tutorial and The third Chapter of Python core programming. However, due to time constraints, SOME adjustments will be made. Crawler and use python to do interface automation and the above mentioned 3 books will also read and output, but not as much basic content as this one, please forgive me ~

The article is linked below: A concise Python tutorial

Finally, sorted out the next brain map, for reference, shoot everyone ~