Introduction (Learn about Python)

If you’re learning Python, you should at least know something about the language and how Python code is executed. The history of Python can be found in baidu encyclopedia if you are interested, but I won’t go into that.

1. What are interpreted and compiled languages?

Computers do not recognize high-level languages, so when we run a high-level language program, we need a “translator” to engage in the process of converting high-level language into machine language that computers can read. The process is divided into two categories, the first is compilation and the second is interpretation.

Compiled language before the program is executed, the compiler will perform a compilation process on the program, the program into a machine language. The translation is not required at runtime, but can be executed directly. The most typical example is the C language.

Interpreted languages do not have this compilation process. Instead, the interpreter interprets the program line by line as it runs, and then runs it directly. Ruby is the most typical example.

Through the above examples, we can summarize the advantages and disadvantages of interpreted languages and compiled languages, because compiled languages have made the “translation” of the program before it runs, so there is no “translation” process during the run, so it is more efficient. However, we should not generalize. Some interpreted languages can also be optimized by interpreter optimization to optimize the entire program as it is translated, thus outperforming compiled languages in terms of efficiency.

In addition, with the rise of virtual machine based languages such as Java, we cannot divide languages into interpreted and compiled languages. Using Java, for example, Java is first compiled into bytecode files by the compiler and then interpreted into machine files by the interpreter at run time. So we say Java is a compile-interpret-later language. Change to C#, which first compiles C# files into IL files using the compiler, and then into machine files using the CLR. So we say C# is a pure compiled language, but C# is a language that requires a second compilation. The same can be applied to other languages based on the.NET platform.

2. So what is Python?

Python, like Java and C#, is a virtual machine based language. Let’s take a look at how Python programs work on the surface.

When we type Python hello.py on the command line, we activate python’s interpreter, telling the interpreter that you need to start working. But before “explaining,” the first thing you actually do is compile, just like in Java.

For those familiar with Java, consider how we execute a Java program on the command line:

javac hello.java
java hello
Copy the code

It’s just that when we use an IDE like Eclipse, we merge the two into one. Python also performs the same process when we run Python hello.py, so we should describe Python as a language that is compiled and then interpreted.

3. Describe the running process of Python

Before we get to that, let’s talk about two concepts, PyCodeObjects and PYC files.

The PyC we see on the hard disk is needless to say, but the PyCodeObject is actually compiled by the Python compiler. So let’s just keep it simple. Let’s keep going.

When a Python program is running, the compiled results are stored in an in-memory PyCodeObject, and when the Python program is finished, the Python interpreter writes the PyCodeObject back to the PYC file.

When the Python program is run a second time, it first looks for pyC files on the hard disk. If it finds them, it loads them directly. Otherwise, the process is repeated.

So we should distinguish PyCodeObject from PYC files by saying that pyC files are actually a persistent form of PyCodeObject.

For more details, see the Python program execution process

Finally:

  • “Life is short. I use Python.”

  • Python’s design philosophy is “elegant,” “clear,” and “simple.”

Variables and strings

First: Python can end each statement without a semicolon; , such as print(‘hello’) prints hello

1.1 variable

If you have a programming background, you don’t need to say much about variables.

Naming of variables:

  • Hump nomenclature
  • PASCAL nomenclature

1.2 the string

1. Basic introduction

Either single quotation marks “” or double quotation marks” “can be used, or ”’ ”’ three quotation marks, three of which are used for long paragraphs of text or instructions. As long as there are more than three quotation marks, you can write as many lines as you like.

Strings can be added directly, for example:

str1 = 'hi'
str2 = 'hello'
print(str1 + str2)
Copy the code

Running results:

hi jaybo
Copy the code

② String multiplication, e.g.

string = 'bang! ' total = string * 3Copy the code

Print the total result:

bang! bang! bang!Copy the code

2. String fragmentation and index

A string can be indexed and fragmented by string[x].

The shredding of a string can actually be viewed as taking what you want to cut out of the string, copying out a little bit of the length you want, and storing it somewhere else, without making any changes to the source of the string. Each string obtained by sharding can be considered a copy of the original string.

Take a look at the following code:

name = 'My name is Mike'
print(name[0])
'M'
print(name[4 -])
'M'
print(name[11:14]) # from 11th to 14th, 14th one is excluded
'Mik'
print(name[11:15]) # from 11th to 15th, 15th one is excluded
'Mike'
print(name[5:)'me is Mike'
print(name[:5])
'My na'
Copy the code

If you are confused, you can understand and analyze by referring to the following table:

: The two sides represent where the string split starts and ends.

Take name[11:14] as an example, the truncated number starts with the 11th character and ends with position 14 but does not contain the 14th character. A notation like name[5:] represents a string fragment from the numbered character 5 to the end. In contrast, name[:5] represents a shard starting with a character numbered 0 to a character numbered 5 but containing the fifth character. It might get confusing, but you can imagine that the first one goes from 5 to the very end, and the programmer is too lazy to count them so he writes them out, and the second one goes from the very end to 5, and he’s too lazy to write zeros, so he writes [:5].

3. String methods

  • Replace method: The first argument indicates the part to be replaced, and the second argument indicates the string to be replaced.

  • Fill in the blank string, for example:

    city = input("write the name of city:"") url = "http://apistore.baidu.com/mri... /weather? citypiny={}.format(city)Copy the code

4, problem,

Question 1:

num = 1
string = '1'
print(num + string)
Copy the code

Will the above code fail?

Explanation: Integers cannot be added directly to strings. We can convert that string to an integer and add it up, int(string)

num = 1
string = '1'
print(num + int(string))
Copy the code

Second, the function

Here are some examples of functions you may have already used:

Check data type: type(STR) String data converted to an integer: int(STR)...Copy the code

Using a function in Python is simply putting the object you’re dealing with in parentheses after a name. In a nutshell, that’s how you use a function, you can stuff it in and get the result. There are other such functions in Python:

In Python3.5, for example, there are 68 such functions, which are called built-in functions. Built-in means that these functions are available when Python is installed.

2.1 Function Format

Define the format of the function:

Def and return are keywords.

Note: the statements after the function indentation are called blocks, and the indentation is for the logic and dependency of the table name statements. Indentation is an issue that can’t be ignored because it will cause your code to fail.

2.2 Function Parameters

① Position parameters, for example, look at the code:

def trapezoid_area(base_up, base_down, height):
    return 1/2 * (base_up + base_down) * height
Copy the code

Next we call this function:

trapezoid_area(1.2.3)
Copy the code

Parameters 1, 2, and 3 correspond to parameters base_UP, base_DOWN, and height respectively. This way of passing in parameters is called positional parameters.

(a=1, b=2, c=3) (a=1, b=2, c=3) (a=1, b=2, c=3)

See below:

  • The function parameters in the first line are passed in reverse order. Because they are keyword parameters, they do not affect the normal operation of the function.
  • On the second line, the function arguments are passed in reverse order, but on the third line, it becomes a position function. Unfortunately, this method is syntactically incorrect, because if passed by position, the last function should be the height position. But height has already been passed a value of 3 by name, so it conflicts.
  • The function arguments on the third line are passed in positive order, the first two as keywords, and the last as positional arguments, but positional arguments cannot be followed by keyword arguments, so they are incorrect.
  • In line 4, the function arguments are passed in positive order, the first two as positional arguments, and the last as keyword arguments. This function works fine.

③ Variable length parameters

Sometimes when we design a function interface, we need variable length parameters. In other words, we cannot determine the number of arguments passed in advance.

Python provides a tuple way to accept arguments that are not directly defined. This way the parameter is preceded by an asterisk *. If no arguments are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to functions. Such as:

def print_user_info( name ,  age  , sex = 'male' , * hobby):
    Print user information
    print('Nickname: {}'.format(name) , end = ' ')
    print('Age: {}'.format(age) , end = ' ')
    print('Gender: {}'.format(sex) ,end = ' ' )
    print('Hobby: {}'.format(hobby))
    return;

Call print_user_info
print_user_info( 'Ming' , 25.'male'.'Play basketball'.'Play badminton'.'running')
Copy the code

Output results:

Nickname: Xiao Ming Age: 25 Gender: Male Hobbies: (' playing basketball ', 'playing badminton ',' running ')Copy the code

According to the output, * Hobby is a mutable argument, and Hobby is actually a tuple.

Variable length parameters also support key parameters. Key parameters that are not defined are placed in a dictionary. In this way, the parameter is preceded by **, as shown in the following example:

def print_user_info( name ,  age  , sex = 'male' , ** hobby ):
    Print user information
    print('Nickname: {}'.format(name) , end = ' ')
    print('Age: {}'.format(age) , end = ' ')
    print('Gender: {}'.format(sex) ,end = ' ' )
    print('Hobby: {}'.format(hobby))
    return;

Call print_user_info
print_user_info( name = 'Ming' , age = 25 , sex = 'male', hobby = ('Play basketball'.'Play badminton'.'running'))
Copy the code

Output results:

Nickname: Xiao Ming24Gender: Male Hobbies: {'hobby': ('Play basketball'.'Play badminton'.'running')}
Copy the code

Comparing the above example with this one shows that ** Hobby is a mutable argument, ** Hobby is a tuple, ** Hobby is a keyword argument, and Hobby is a dict.

④ Only keyword parameters are accepted

Keyword arguments are easy to use and not prone to error. What if we define a function that wants to force keyword arguments to be passed? This can be done by placing the mandatory keyword argument after an * argument or a single *, as in:

def print_user_info( name , *, age, sex = 'male' ):
    Print user information
    print('Nickname: {}'.format(name) , end = ' ')
    print('Age: {}'.format(age) , end = ' ')
    print('Gender: {}'.format(sex))
    return;

Call print_user_info
print_user_info( name = 'Ming' ,age = 25 , sex = 'male' )

The age and sex parameters are forced to use keyword arguments
#print_user_info(' xiao Ming ', 25, 'male')
print_user_info('Ming',age='22',sex='male')
Copy the code

As you can see from the example, if age, sex does not apply keyword arguments will report an error.

2.3 Anonymous Functions

Ever wanted to define a very short callback function, but didn’t want to write a function that long in def form, so is there a shortcut?

The answer is yes.

Python uses lambda to create anonymous functions, that is, instead of defining a function in the standard form of def statements.

Anonymous functions have the following characteristics:

  • Lambda is just an expression, a function body ratiodefMuch easier.
  • The body of a lambda is an expression, not a block of code. Only a limited amount of logic can be encapsulated in lambda expressions.
  • Lambda functions have their own namespace and cannot access arguments outside their own argument list or in the global namespace.

Basic syntax: lambda [arg1 [,arg2,…..argn]]:expression

Example:

sum = lambda num1 , num2 : num1 + num2;
print( sum( 1 , 2))Copy the code

Output: 3

Note: Although lambda expressions allow you to define simple functions, their use is limited. You can only specify a single expression whose value is the final return value. That means no more language features, including multiple statements, conditional expressions, iterations, exception handling, and so on.

There is a particular problem with anonymous functions. For example, change the above example:

num2 = 100
sum1 = lambda num1 : num1 + num2 ;

num2 = 10000
sum2 = lambda num1 : num1 + num2 ;

print( sum1( 1 ) )
print( sum2( 1))Copy the code

What do you think the output is? The first output is 101, the second output is 10001, the result is not, the output is like this:

10001, 10001,Copy the code

This is mainly because num2 in a lambda expression is a free variable that is bound to its value at run time, not at definition, unlike the function’s default parameter definition. So the recommendation is to use the first solution in this case.

Loop and judgment

3.1 Boolean expressions and judgments

Boolean values in Python: True and Flase. Note that both are capitalized.

Any expression that produces a Boolean value is a Boolean expression:

1 > 2 # False
1 < 2 <3 # True
42! =The '42' # True
'Name'= ='name' # False
'M' in 'Magic' # True
number = 12
number is 12 # True
Copy the code

Note 1: Objects of different types cannot be compared with <, >, <=, =>, but can be compared with == and! =.

Note 2: Floating-point and integer types, although different types, do not affect the comparison operation. And, not equal to! = You can write <>.

So, can Boolean types be compared? True > Flase, the answer is yes, Ture and Flase are just like 1 and 0 to a computer, so the result is True, i.e.

3.2 Conditional control

Definition format:

This construction works in one sentence: If… If the condition is true, do… ; If not, do…

A conditional expression is a Boolean expression that returns True.

3.3 cycle

(1) the for loop

To sum up what the for loop does is this:… Each of these elements, do… Things.

Print the multiplication table:

for i in range(1.10) :for j in range(1, i+1):
        print('{}x{}={}\t'.format(i, j, i*j), end=' ')
    print()
Copy the code

Running results:

1x1=1
2x1=2   2x2=4
3x1=3   3x2=6   3x3=9
4x1=4   4x2=8   4x3=12  4x4=16
5x1=5   5x2=10  5x3=15  5x4=20  5x5=25
6x1=6   6x2=12  6x3=18  6x4=24  6x5=30  6x6=36
7x1=7   7x2=14  7x3=21  7x4=28  7x5=35  7x6=42  7x7=49
8x1=8   8x2=16  8x3=24  8x4=32  8x5=40  8x6=48  8x7=56  8x8=64
9x1=9   9x2=18  9x3=27  9x4=36  9x5=45  9x6=54  9x7=63  9x8=72  9x9=81
Copy the code

(2) the while loop

Conclusion: As long as… As soon as the condition is established, keep doing…

During a loop, you can skip the loop with break and skip the loop with continue.

In Python’s while loop, we can use else statements, while… Else Executes the else block when the loop condition is false. Such as:

count = 0
while count < 3:
   print (count)
   count = count + 1
else:
   print (count)
Copy the code

Running results:

0
1
2
3
Copy the code

A while… Else statement, for… Else statements are the same as normal statements. Else statements are executed when the loop completes normally (i.e., for is not broken by a break), while… Same thing with else. Such as:

for num in range(10.20) :Iterate over numbers between 10 and 20
   for i in range(2,num): # Iterating by factor
      if num%i == 0:      # determine the first factor
         j=num/i          # Compute the second factor
         print ('%d is a composite ' % num)
         break            # exit the current loop
   else:                  # else part of the loop
      print ('%d is a prime ' % num)
Copy the code

Running results:

10 is a composite number 11 is a prime number 12 is a composite number 13 is a prime number 14 is a composite number 15 is a composite number 17 is a prime number 18 is a composite number 19 is a prime numberCopy the code

Data structure

Python has four types of data structures: lists, dictionaries, tuples, and collections. Let’s take a look at the four data structures as a whole:

list = [val1,val2,val3,val4] # list
dict = {key1:val1,key2:val2} # dictionary
tuple = (val1,val2,val3,val4) # tuples
set = {val1,val2,val3,val4}	# set
Copy the code

4.1 List

  1. Each element in the list is mutable;

  2. The elements in a list are ordered, that is, each element has a place;

  3. The list can hold any object in Python. As follows:

    all_in_list = [
        1.# integer
        1.0.# floating point number
        'a word'.# string
        print(1), # function
        True.# Boolean value
        [1.2].# list within list
        (1.2), # tuples
        {'key':'value'} # dictionary
    ]
    Copy the code

In addition, for data operations, the most common is to add, delete, change and check. Omitted here, look for next corresponding function on the net to practice can fall.

4.2 Dict

  1. The data in the dictionary must be in key-value pairs;

  2. Logically, a key cannot be repeated;

  3. A key in a dictionary is immutable, that is, cannot be changed, while a value is mutable, modifiable, and can be any object.

    Here’s an example:

    NASDAQ_code = {
        'BIDU':'Baidu'.'SINA':'Sina'.'YOKU':'Youku'
    }
    Copy the code

Keys and values in a dictionary do not exist without each other. If you write {‘BIDU’:} it raises an invalid syntax error.

If you try to build a dictionary by using a mutable element as a key, such as a list: key_test = {[]:’a Test’}, an error is reported: unhashable type:’list’.

And the keys in the dictionary are never duplicated, and even if you do, the same key can only appear once: a = {‘key’:123,’key’:123}.

Add, delete, change and check operations are omitted here.

Remark:

  • The method used to add multiple elements to the list isextend, adding multiple elements to the dictionary isupdate()
  • Dictionaries can’t be sliced, so it’s wrong to write:chart[1:4]

4.3 Tuple

A tuple can be thought of as a stable version of a list, because tuples cannot be modified, so methods that exist in lists cannot be used on tuples, but tuples can be indexed in the same way as lists.

letters = ('a, 'b', 'c', 'd')
letters[0]
Copy the code

Relevant operations to find code practice can be.

4.4 Set (Set)

Sets are closer to the mathematical concept of sets. The elements in each set are random objects without repetition. We can judge the dependency of data through sets, and sometimes we can subtract the repeated elements in data structures through sets.

Collections cannot be sliced or indexed. In addition to performing collection operations, collection elements can be added and removed:

a_set = {1.2.3.4}
a_set.add(5)
a_set.discard(5)
Copy the code

4.5 Some tips on data structures

4.5.1 Multiple Loops

As follows:

Code demo:

for a, b in zip(num, str):
    print(b, 'is', a)
Copy the code

4.5.2 derivated

The use of list comprehensions is well understood and can be easily viewed in two parts. The diagram below:

After the red dotted line is the familiar expression for the loop, and before the dotted line we can think of the elements we want to put in the list.

Code demo:

a = []
for i in range(1.11):
    a.append(i)
Copy the code

This can be written as list parsing:

b = [i for i in range(1.11)]
Copy the code

List parsing is not only convenient, but also far more efficient.

Fifth, the understanding of class

5.1 Introduction to classes

Class definition:

class CocaCola:
    formula = ['caffeine'.'sugar'.'water'.'soda']
Copy the code

Using class to define a class is as simple as using def to define a function when creating a function. As you can see above, the class named CocaCola is defined, and then in the indentation there is a formula that holds the list of variables. The variables defined in the class are the variables of the class, and the variables of the class have a special term, we call them the attributes of the class.

Class attributes:

  • Class variables
  • methods

Class instantiation:

coke_for_me = CocaCola()
coke_for_you = CocaCola()
Copy the code

② Class variable attribute reference: CocaCola. Formula, coke_for_me. Formula

Use of class methods:

class CocaCola:
    formula = ['caffeine'.'sugar'.'water'.'soda']
    def drink(self):
        print('Energy! ')
coke = CocaCola()
coke.drink()
Copy the code

Results:

Energy!
Copy the code

5.2 the self

I think a lot of people have noticed the odd thing about the self argument that doesn’t seem to be of any use. To illustrate the principle, it’s actually very simple. Let’s modify the above code:

class CocaCola:
    formula = ['caffeine'.'sugar'.'water'.'soda']
    def drink(coke):	# change self to coke
        print('Energy! ')
coke = CocaCola()
coke.drink()
Copy the code

Results:

Energy!
Copy the code

What do you think? We got some ideas! This parameter is the instance itself being created. Once a class is instantiated, we can actually use it in a similar way to how we use functions:

coke = CocaCola
coke.drink() == CocaCola.drink(coke) # The left and right sides are written exactly the same
Copy the code

The instantiated object is silently passed by the compiler as the first argument to the following method in parentheses. It’s the same thing, but we’re going to write it more like that. The name of the self parameter can be changed at will (the compiler does not give an error for this).

Like functions, methods of a class can have arguments of their own, as follows:

class CocaCola: formula = ['caffeine','sugar','water','soda'] def drink(self,how_much): if how_much == 'a sip': Print ('Cool ') elif how_much == 'whole bottle ': print('Headache! ') ice_coke = CocaCola() ice_coke.drink('a sip')Copy the code

Results:

Cool~
Copy the code

5.3 Magic Method

There are some methods in Python classes called “magic methods,” and _init_() is one of them.

class CocaCola():
    formula = ['caffeine'.'sugar'.'water'.'soda']
    def __init__(self):
        self.local_logo = 'Coca-Cola'
    def drink(self): 
        print('Energy! ')
coke = CocaCola()
print(coke.local_logo)
Copy the code

What it does: It does a lot of things before creating the instance. To put it bluntly, this means that even if you create an instance without referring to the init_() method, its statements will be executed automatically first. This provides a great deal of flexibility in how classes are used.

class CocaCola:
    formula = ['caffeine'.'sugar'.'water'.'soda']
    def __init__(self,logo_name):
        self.local_logo = logo_name
    def drink(self):
        print('Energy! ')
coke = CocaCola('ݢ ݗ ݢ Ԕ')
coke.local_logo
>>> Coca-ColaCopy the code

It is easy to understand if you have experience with object-oriented programming, which is the “constructor” in many object-oriented languages.

5.4 Inheritance of classes

The following code:

class CaffeineFree(CocaCola):
    caffeine = 0
    ingredients = [
        'High Fructose Corn Syrup'.'Carbonated Water'.'Phosphoric Acid'.'Natural Flavors'.'Caramel Color',
    ]
coke_a = CaffeineFree('Cocacola-FREE')
coke_a.drink()
Copy the code

Represents CaffeineFree inherits the CocaCola class.

Variables and methods in a class can be inherited by subclasses, but can also be overridden if special changes are required.

Q1: If a class attribute is reassigned, will it affect the reference of the class attribute?

class TestA(a):
    attr = 1
obj_a = TestA()

TestA.attr = 24
print(obj_a.attr)

>>> Results:24
Copy the code

A1: It does.

Q2: Does the reassignment of instance attributes affect the reference to class attributes?

class TestA:
    attr = 1
obj_a = TestA()
obj_b = TestA()

obj_a.attr = 42
print(obj_b.attr)

>>> Results:1
Copy the code

A2: No impact.

Q3: Class attributes Instance attributes have the same name, then. What will be quoted later?

class TestA(a):
    attr =1
    def __init__(self):
        self.attr = 24

obj_a = TestA()

print(obj_a.attr)

>>> Results:24
Copy the code

A3: the value after the class attribute is assigned.

Summary: As you can see, Python references properties from the outside in. When you create an instance and are ready to reference a property, the compiler searches to see if the instance has the property, and if so, references it. If not, the class to which the instance belongs will be searched to see if it has the property. If so, the reference will be made. If not, an error will be reported.

Use third-party libraries

6.1 Installing your Own Library

We usually use PIP to install third-party libraries, so how do we install our own libraries? Of course you can submit your own library to PIP, but you need to add a certain amount of code and the necessary files. Here we use a simpler method:

  1. Go to your Python installation directory and find the followingsite-packagesFolder.
  2. Remember your file name, because it will be the name of the reference, and put in the py file you wrote.

This folder should contain all the third-party libraries you have installed. If you don’t know your installation path, try using the following methods to find out where it is:

import sys
print(sys.path)
Copy the code

It will print out a list, and the fourth in the list will be where your library installation path is, so you can also do this directly:

import sys
print(sys.path[3])
Copy the code

6.2 Installing third-party Libraries

Amazing third party library

If a phone is a metaphor for programming languages, Python is a smartphone. Just as many mobile apps are available on iOS and Android, there are a variety of third-party libraries that provide Python developers with great convenience.

When you want to build a website, you can use web frameworks such as Django, which is fully functional, and Flask, which is lightweight. When you want to write a small game, use the PyGame framework; When you want to create a crawler, use a Scrapy frame. When you want to do statistical analysis, you can use the Pandas data framework…… There are so many resources that can help us do what we want to do efficiently and quickly that we don’t have to reinvent the wheel.

So how to find the appropriate library according to your needs? You can go to awesome-python.com, which has a full collection of third-party libraries, to find them by category. For example, if you want to crawl out of the aspects of the library, check the Web Crawling category, you will see the corresponding third-party library sites and descriptions, you can go to the library’s website for more details, and confirm that the library supports Python 2 or Python 3, but most commonly used libraries already support both. Alternatively, you can look directly through the search engines.

Installing third-party libraries:

① The easiest way: Install in PyCharm

  1. Select File –> Default Setting from the PyCharm menu
  2. Search Project Interpreter, select the current Version of Python, and click “+” to add the library
  3. Enter the name of the library, check it, and click Install Package

PyCharm will indicate success after a successful installation. You can also view which libraries are installed in the Project Interpreter screen, and click the “-” sign to uninstall libraries that are no longer needed.

② The most direct way: in the terminal/command line installation

PyPI (Python Package Index) is an official repository of Python third-party libraries. PyPI recommends using the PIP Package manager to download third-party libraries.

  1. Install the PIP

    After Python 3.4, PIP can be supported directly by installing a Python environment. You can check by typing this in the terminal/command line: PIP –version (if the PC path path is already configured), if the PIP version is displayed, it indicates that the PIP has been successfully installed. If no, install it based on the system:

    • How do Windows users install it
    • How do Mac users install it
    • How do Linux users install it
  2. Use the PIP installation library

    After installing PIP, to install the library, simply type pip3 install PackageName on the command line (note: if you want to install pip3 into Python 2, you need to change pip3 to PIP). Supplement:

    • PIP and PIp3 in PYTHon3
    • The difference between PIP and PIp3 is used after python3 is installed

    PIP and pip3 are both in the Python36\Scripts\ directory. If python2 and python3 are installed, PIP is used by default for python2 and pip3 is specified for Python3. PIP and PIp3 are equivalent if python3 is installed only.

    Python3 -m PIP install PackageName python3 -m PIP install PackageName If you want to install into Python2, you need to replace Python3 with Python.)

    If you have permission problems, enter sudo PIP install PackageName

    Successfully Insyalled PackageName is displayed after the installation is successful

    Some common PIP directives:

    PIP  [options] package_name
    
    pip install package_name==1.92.	Install the specified version of the package
    pip install --upgrade package_name	Update the specified package
    pip uninstall package_name	Unmount the specified package
    pip show package_name	View the details of the installed package
    pip list	View all installed packages
    pip --help	# View help
    Copy the code

Bonus: If downloads are slow, consider changing the PIP download source. Domestic mirrors are:

# # # domestic commonly used image http://pypi.douban.com/simple/ douban http://mirrors.aliyun.com/pypi/simple/ ali Tsinghua http://pypi.mirrors.ustc.edu.cn/simple/ https://pypi.tuna.tsinghua.edu.cn/simple # # university of science and technology of China http://pypi.hustunique.com/simple/ # huazhong university of science and technologyCopy the code

Change method:

  1. The temporary use, add the -i or – index parameters: PIP install -i http://pypi.douban.com/simple/ flask

  2. This configuration method takes effect permanently in Linux

    PIP sudo vim pip.conf # $HOME mkdir. PIP CD. PIP sudo vim pip.conf # Or use time will prompt untrusted [global] index-url=https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host=pypi.tuna.tsinghua.edu.cn disable-pip-version-check=true timeout = 6000Copy the code
  3. The configuration method that takes effect permanently in Windows

    \Users\username\AppData\Local\ PIP or C: Users\username\ PIP # b, create "PIP. Ini" file (note: Encoded in UTF-8 without BOM format), Add the following content [global] index-url=https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host=pypi.tuna.tsinghua.edu.cn disable-pip-version-check=true timeout = 6000Copy the code

The most primitive way: manual installation

Go to pypi.python.org and search for the name of the library you want to install. There are three possibilities:

  1. The first type is exe, which is the most convenient. Download the exe for your computer and Python environment, and click Next to install it.

  2. The second is the.whL class file, which has the benefit of automatically installing dependent packages.

    1. Go to the command line and enterpip3 install whellWait for execution to complete without error (PIP in Python 2)
    2. Confirm your download from Explorer.whlPath to the class file, then continue on the command line:cd C:\download“, you need to change your path. The meaning of path is the folder where the file is located, excluding the name of the file itself, and then enter the following command line:pip3 install xxx.whl.xxx.whlIs the full filename of the file you downloaded.
  3. The third is the source code, probably in zip, tar.zip, tar.bz2 format, this method requires that the user has installed the package depends on other packages. For example, pandas relies on numpy. This method will not work if you do not install NUMpy.

    1. Decompress the package, enter the decompressed folder, usually you will see onesetup.pyCheck the path of the file you downloaded from Explorer, open the command line, and type:cd C:\downloadHere you need to change to your path. The meaning of path is the folder where the file is located, not including the file name itself
    2. Then continue on the command line:python3 setup.py installWith this command, you can install the third-party library into your system, which is your Python pathC: \ Python3.5 \ Lib \ site - packages.

    Note: To unload a library, go to the Python directory, go to the site-Packages folder, and delete the library files there.

Most of the content of this article comes from:

  • The Turing Community: The First Python Primer for Programmers