Welcome to “Python From zero to one ”, Here I'm going to share an appointment 200 piece Python Series articles , Take everyone to study and play together , have a look Python This interesting world . All articles will be combined with cases 、 Code and author's experience , I really want to share my nearly ten years programming experience with you , I hope it will be of some help to you , There are also some shortcomings in the article .
Python The overall framework of the series includes basic grammar 10 piece 、 Web crawler 30 piece 、 Visual analysis 10 piece 、 machine learning 20 piece 、 Big data analysis 20 piece 、 Image recognition 30 piece 、 Artificial intelligence 40 piece 、Python Security 20 piece 、 Other skills 10 piece . Your attention 、 Praise and forward is the greatest support for xiuzhang , Knowledge is priceless, man has love , I hope we can all be happy on the road of life 、 Grow up together .
This paper refers to the author and Mr. Xu CSDN The article , I really recommend you to study .
meanwhile , The author's new “ Na Zhang AI Safe house ” Will focus on Python And security technology , Mainly share Web penetration 、 System security 、 Artificial intelligence 、 Big data analysis 、 Image recognition 、 Malicious code detection 、CVE Reappear 、 Threat intelligence analysis, etc . Although the author is a technical white , But it will ensure that every article will be carefully written , I hope these basic articles will help you , stay Python And on the road to safety, progress with you .
Why study Python?
I'm learning Python Before , You don't have to worry about not having a foundation or “ Stupid brain ”, I always thought , As long as you want to learn and work hard for it , You can learn , Can use Python To do a lot of things . In this noisy era , A lot of technologies or concepts will continue to emerge , I hope you can settle down and study , Don't rush things , One step at a time . When you learn a technique well 、 After learning , There are still things that can be done , You can even find a job you like or finish a practical project .
Programming language is not the best , Only the best fit . As a beginner , I highly recommend that you study Python, Why? ? On the one hand, it has clear grammar 、 Code friendly 、 High readability , meanwhile Python With powerful third-party library functions , Including network crawling 、 Data analysis 、 visualization 、 Artificial intelligence, etc ; On the other hand Python It's an interpretive programming language , It's an object-oriented language again , Its operability and portability are high , It is widely used in data mining 、 information acquisition 、 Artificial intelligence 、 Network security 、 Automatic testing and other fields . even to the extent that , Many pupils 、 High school courses and computer level 2 have also been increased Python.
Python advantage
Python The biggest advantage is efficiency . Sometimes the efficiency of programmers or researchers is more important than the efficiency of machines , For many complex functions , Using a clearer language can reduce the burden on the program , This greatly enhances the quality of the program , Its easy to learn and expansibility can also let the novice quickly start . although Python The bottom layer runs faster than C Slow language , but Python Clear structure frees programmers of their time , At the same time very convenient and other programming language code ( Such as C Language ) Merge together .
therefore , There has never been a programming language like Python It's rooted in so many fields at the same time , also Python Support cross platform operations , It also supports open source , Have a strong third-party library . Especially with the continued popularity of artificial intelligence ,Python stay IEEE The most popular languages released in recent years have ranked number one , More and more app enthusiasts 、 Technology followers are also learning Python.
Python Study suggest
stay Python Learning process , Don't feel like you have a thin foundation or haven't touched before , Just want to give up , A lot of people don't choose to start or quit the race . I think , Just calm down , Willing to work hard , You can learn . In the learning process , Be sure to write code 、 Write code 、 Write code , I'm just starting to practice , Can accumulate slowly .
meanwhile , It's common to make mistakes in the process of writing code , I write now Python The code doesn't make mistakes every day , I was in a panic , So there was an error , Learn Baidu 、 It's really important for Google to solve this problem , It is also an improvement of your learning ability , There was no mistake , You can go to the open source forum 、 Community 、 Ask questions in Study Group , Welcome to the official account or CSDN Look for me .
Next, I'd like to give the recommendation of teacher Xu Python Programmer Growth Roadmap , Include : Basic grammar –> Language sense training –> Project practice –> Continue learning in different directions –> Intermediate programmer –> Expand depth and breadth –> Senior programmer .
here , Give me learning Python Some of the process and skills of . I was the first to contact Python yes 2013 year , It's mainly because graduate students are majoring in natural language processing , Need to pass through Python Grab the data and analyze it , So I chose it . In those years Python There is very little information about , It's not that hot , But it has always been , Specific suggestions are as follows :
There is no shortcut to learning , Only insist on , But you can get through Python Constantly improve your interest in learning , Do something you like , Love the language . Finally, I give my junior year's study Python Words to motivate yourself :
If not now, when? If not me, who?
If it's not for yourself , For whom ; If it wasn't for fighting now , When will it start ?
Python Is the Dutch Guido van Rossum stay 1989 A new script interpretation language developed in , It is an object-oriented interpretive computer programming language .Python It's pure free software , Its grammar is concise and clear , One of the features is the mandatory use of white space (White Space) Indent as a statement . because Python Has a rich and powerful library , Often nicknamed glue language .
Python As a hot language , It has the following characteristics :
The author and Mr. Xu have the same point of view , It is not recommended for beginners to choose something like Anaconda or PyCharm And other integration tools , In my opinion, the convenience they provide is not as much as the trouble for users to learn . At least , Don't use... In the first week IDE. about Python Such an interpretive scripting language , A handy editor is enough .
Of course , These tools follow as you learn , The author will also popularize and share its functional usage .
If you choose Windows Programming under the system , You can use the Python Official website Downloads Download the programming software from the page , Its official website is “http://www.python.org”. meanwhile , If you are in Linux Compiled under the system Python Code , You can use the Linux The system has built-in installation and use Python Interpreter .
from Python When downloading from the official website , Please pay attention to choose the correct version . If it's for learning , There's no problem downloading the latest version , If it is used for production , Consider whether the third-party modules you need to develop support the latest version of Python. Be careful ,Python2 It has not been updated , I suggest that you learn Python3, They are basically similar in grammar , Only partial function modification . Here the author chooses to download Python3.6 or Python3.7.
Don't forget to check the bottom two check boxes when installing , Otherwise, it will bring some trouble to the follow-up module installation , It is recommended to install by default .
After successful installation , Need to be in “ Start ” Select... From the menu “ Program ”, Successfully installed Python Software , As shown in the figure , Open interpreter writing Python Code .
open “Python 3.6(64-bit)” Command line software , Enter the first line Python Code “I love python”, The output result is shown in the figure below . The advantages of interpretive language , You can write a sentence and execute a sentence , Where to think and where to write , You don't have to write everything like a compiled language , It can only be run after the compilation is successful . I particularly like to use python Of IDLE, Even use it as a calculator .
But if you need to write large pieces of code or custom functions ,Python The command line is certainly not a good choice , At this point, readers can click “IDLE”, function Python Integrated development environment (Python Integrated Development Environment,IDLE), You can use it to create or open .py Script files , Can edit 、 Operation and commissioning , Open as shown in the figure below .
Then you can click “File” in “New File” New file , And save as py file , Such as “test01.py”, Then click Run “Run Module F5” Button , function Python Script files .
all Python The file will be .py Extension name . Write the source code in test01.py Run... In file .
A lot of times , We use it IDLE Verify that the code is written correctly , Check whether the module is successfully installed and the version number .IDLE Support tab Key auto complement , Often use this function to view the methods and properties of an object . Tips :
- tab Key auto complement
- Move the cursor over the executed statement and hit enter , You can repeat this command
- Underline (_) You can get the last execution result
The front has been successfully installed Python Software , Let's start with Python Basic grammar of , Include indents and comments 、 Variables and constants 、 Input and output 、 Assignment, expression, etc .
Indent
Different from other languages , stay Python The hierarchical relationship of code is indicated by indenting in .1 An indent is equal to 4 A space , It is Python The only way to indicate the framework of a program in a language .
stay Python in , Each statement in the same statement block is indented , And indent the same amount , When a statement block is rolled back or has been closed , You need to back off the indent of the previous level , Indicates the end of the current block . Here is C Language and Python Comparison of grammar , among C Language uses curly braces to distinguish hierarchical relationships ,Python Distinguish by indenting .
The number of indented blanks is variable , But all code block statements must contain the same amount of indented white space , This must be strictly enforced .
Python quotes
Python You can use quotation marks ( ’ )、 Double quotes ( " )、 Three quotes ( ‘’’ or “”" ) To represent a string , The beginning and end of a quotation mark must be of the same type . Three quotation marks can be made up of multiple lines , Write fast syntax for multiline text , Commonly used for document strings , At the specific location of the document , As a comment .
word = 'eastmount'
sentence = " Na Zhang AI Safe house "
paragraph = """ This is a paragraph .
Contains multiple statements """
notes
Comments are used to describe code information , Comment code is not executed .Python There are two main types of annotations :
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# file name :test01.py
# The first note
print ("Hello World!") # The second note
"""
Created on Sat Sep 16 10:34:31 2017
@author: yxz
"""
Multi line statement
Python In a statement, a new line is usually used as the end of the statement . But we can use slashes ( \) Divide a line of statements into multiple lines to display , As shown below :
total = item_one + \
item_two + \
item_three
The statement contains [], {} or () Brackets do not need to use multiline connectors . The following example :
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Variable
Variables are elements that can change values in a program , Is a named storage location in memory , The name of a variable that represents or refers to a value , For example, I hope to use N representative 3,name representative “hello” etc. . The naming rules are as follows :
['and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
differ C/C++/Java Other languages ,Python Variables in do not need to be declared , You can directly use the assignment operator for its assignment operation , The data type is determined according to the assigned value , The figure below shows the type of undeclared output .
Constant
A constant is an element that does not change the value of a program , A fixed value that cannot be modified once initialized , It's a unit in memory that holds fixed values . For some reason ,Python No information such as C/C++/Java Same const Modifier , In other words ,python There is no keyword that defines constants . however Python You can use object methods to create constants , Such as through const.py file , take const Class register to sys.modules Global dictionary
Output
Output usage print() Function implementation , Include output character information or variables , stay Python2 in , The output includes two formats :print a or print(a), Represents the output variable a Value . but Python3 Whitespace output is no longer supported , If you used Python2, We need to pay attention to these differences .
If you need to output multiple variables , Then use commas to connect , Such as print(a,b,c). A simple example is shown in the following figure ,print() Functions can output various types of variables .
meanwhile ,Python Support format output data , Need to call format() Function implementation , Its output format is :print(format(val,format_modifier)), The parameter val Indicated value 、format_modifier Format word , An example is shown in the figure below .
among “6.2f” Indicative output 6 Floating point number of digit value , To two places after the decimal point , The last bit of the output value is calculated by rounding , The final output is “12.35”.“.2%” Represents the percentage of output , Keep two significant digits , The output is “34.56%”. If you want to output an integer, use “.0f” that will do .
Input
Python The input mainly includes input() and raw_input() Two functions .
>>> str1 = input("input:")
input:"I am a teacher"
>>> print(str1)
I am a teacher
>>> age = input("input:")
input:25
>>> print(age,type(age))
25 <class 'str'>
>>>
>>> str1 = raw_input("input:")
input:hello world
>>> print(str1)
hello world
>>> age = raw_input("input:")
input:25
>>> print(age,type(age))
25 <type 'str'>
>>>
Be careful ,raw_input yes 2.x Version of the input function , Error will be reported in the new version environment , The function is undefined . stay 3.x It should be used in the version input() Instead of raw_input().
assignment
Python The assignment statement in is using the equal sign (=) Assign values to variables directly , Such as “a=10”. If you need to assign values to multiple variables at the same time , The expression is as follows :
It calculates the right side first N Expression , Then assign the result of the expression to the left variable at the same time . Examples are as follows :
>>> a,b,c = 10,20,(10+20)/2
>>> print(a,b,c)
10 20 15.0
>>>
expression
An expression is a line of code in a program that generates or evaluates new data values , The assignment expression is as follows a=10, Usually by variables 、 Constants or operands produce expressions . To define an expression, pay attention to a few points :
End of story Python After basic knowledge , Let the author lead you to know Python Common data types .
Python Common numeric types include integer types 、 Floating point type 、 Plural type .
>>> z = -12.3 + 8j
>>> print(z, type(z))
(-12.3+8j) <type 'complex'>
>>> print(z.real, z.imag)
-12.3 8.0
Be careful :Python The number types in Chinese can be converted to each other , Where floating-point numbers are called int() Function to integer , Such as int(3.14) Return results 3, Integer call float() Convert to decimal , Floating point call complex() Function to complex number .
The string type is Python Middle refers to a character or string that needs to be enclosed in single or double quotation marks . This type calls type(‘Python’) The result is str type . It is generally recorded as :
A string represents a sequence of characters , Its leftmost end represents the starting position of the string , Subscript to be 0, Then increase in sequence . The number corresponding to a string is called “ Indexes ”, such as str1=‘Python’, be str1[0] Get the first character , namely “P” Letter , And strings provide some operations and functions for users to use , such as len(str1) Calculate string length , The return result is 6.
counter = 100 # Assign an integer variable
miles = 1000.0 # floating-point
name = "Eastmount" # character string
python There are two order of values in the string list of :
If you want to get a substring from a string , have access to [ Header subscript : Tail subscript ] To intercept the corresponding string , The subscript is from 0 From the beginning , It can be positive or negative , The subscript can be empty to indicate that the head or tail is taken .[ Header subscript : Tail subscript ] The substring obtained contains the character of the header and subscript , But characters that don't contain trailing subscripts . such as :
>>> s = 'abcdef'
>>> s[1:5]
'bcde'
The list is Python A very important data type in , It's in brackets ([ ]) A collection of comma separated elements in , Can be accessed through a single element in the list , And every element is ordered . for example :
>>> list1 = [1, 2, 3, 4, 5]
>>> print(list1)
[1, 2, 3, 4, 5]
>>> print(list1[0])
1
>>> print(type(list1))
<type 'list'>
>>> list2 = ['I', 'am', 'a', 'teacher']
>>> print(list2)
['I', 'am', 'a', 'teacher']
>>> print(list2[3])
teacher
>>>
List can complete the data structure implementation of most collection classes . It supports characters 、 Numbers 、 Strings can even contain lists ( That is, nesting ). List with [ ] identification , yes Python The most common composite data type .
The cutting of the values in the list can also use variables [ Header subscript : Tail subscript ] , You can intercept the corresponding list , Left to right index default 0 Start , Right to left index default -1 Start , The subscript can be empty to indicate that the head or tail is taken .( Refer to the figure below runoob Website , I recommend you to study )
Each element in the list can define a different data type , Such as list1 = [1, 1.3, ‘teacher’]. The operation method is similar to string , If the list uses the plus sign (+) Splicing 、 Use multiplier sign (*) Repeat display 、 You can also slice to get the child elements in the list , Examples are as follows :
>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8]
>>> print(list1+list2)
[1, 2, 3, 4, 5, 6, 7, 8]
>>> print(list2*3)
[6, 7, 8, 6, 7, 8, 6, 7, 8]
>>> print(list1[2:4])
[3, 4]
>>>
The common methods in the list are shown in the following table , Hypothetical existence list list1 = [4, 2, 1, 5, 3].
Tuple is a data type similar to a list , It uses parentheses to define a collection of one or more elements , Its return type is tuple. Examples are as follows :
>>> t1 = (12, 34, 'Python')
>>> print(t1)
(12, 34, 'Python')
>>> print(type(t1))
<type 'tuple'>
>>> print(t1[2])
Python
>>>
Be careful : Empty tuples can be defined , Such as t2=(), Tuples can be accessed by index , Such as the above code t1[2] Access No. 3 Elements , namely “Python”. When a tuple is defined, it cannot be changed , You can't delete , This is different from a list , Due to the immutability of tuples , Its code is more secure .
The following is a tuple invalid , Because tuples are not allowed to be updated , The list is allowed to be updated . Error message :TypeError: ‘tuple’ object does not support item assignment, An error or... In a programming construct BUG It's very normal , Mo panic , Get rid of it .
# -*- coding: UTF-8 -*-
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Illegal application in tuple
list[2] = 1000 # In the list are legitimate applications
Dictionaries (dictionary) Except for the list python The most flexible type of built-in data structure . A list is an ordered collection of objects , A dictionary is an unordered collection of objects . The difference between the two is : The elements in the dictionary are accessed by keys , Instead of accessing by offset .
Dictionaries are provided for non sequential sets , Dictionary use "{ }" identification , By key value pair (< Key > < Value >) form , A dictionary is a collection of key value pairs , The type of dict. The key is the index of the dictionary , A key corresponds to a value , The key value can be used to find the information in the dictionary , This process is called mapping .
Examples are as follows , It can be obtained through key value pairs “4” Corresponding “Guiyang”.
>>> dic = {
"1":"Beijing","2":"Shanghai","3":"Chengdu","4":"Guiyang"}
>>> print(dic)
{
'1': 'Beijing', '3': 'Chengdu', '2': 'Shanghai', '4': 'Guiyang'}
>>> print(dic["4"])
Guiyang
There are several main differences between dictionaries and lists :
Dictionary key values are very important for flexible applications , Especially web crawlers Json Format parsing , We will use it later in the actual case . Here is a simple code , The key is keys() and values() usage .
dict = {
}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {
'name': 'runoob','code':6734, 'dept': 'sales'}
print(dict['one']) # The output key is one Value
print(dict[2]) # The output key is 2 Value
print(tinydict) # Output complete dictionary
print(tinydict.keys()) # Output all keys
print(tinydict.values()) # Output all values
The output result is shown in the figure below :
I think string operation is also Python A very useful place , Whether it's data crawling 、 Big data analysis or text mining , Therefore, the author will take out this part separately to explain .
A string is an ordered set of character sequences , single quote 、 Double quotes 、 triple ( It can be done either alone or in pairs ) Quote , The string variable enclosed in triple quotation marks can be used to define the newline string . such as :
str1 = 'hello world'
str2 = "hello world"
str3 = """hello world"""
String supports formatted output , We need to introduce the operator percent sign (%) Realization , Place a formatted string to the left of the percent sign , Place the desired formatted value on the right side , But also tuples and dictionaries . for example :
>>> print("Hi!My Name is %s,I am %d years old and %f pounds heavy."%("YXZ", 26, 55.5))
Hi!My Name is YXZ,I am 26 years old and 55.500000 pounds heavy.
>>>
Output string in turn (%s)、 Integers (%d)、 Floating point numbers (%s) Three values . At the same time, strings support a variety of operations , Especially when dealing with text content , You need to use these methods and functions , Common functions are explained below .
Basic operation
The basic operations of a string include finding the length 、 Splicing 、 Repeat 、 Indexes 、 Slice and so on . hypothesis str1 String is “hello”,str2 String is “world”, be len(str1) Compute string str1 The length is 5;str1+str2 The result of splicing is “helloworld”;str1*3 The string is repeated and the result is “hellohellohello”.
String slicing is defined as s[i:j:step], among step Indicates the direction of the slice , Default start from 0 Start , Cut to the end without writing . for example :
str1 = 'abcdefghijklmn'
print(str1[3:6])
# def
The output is “def”, From 3 Values to get , The first 6 Value is the end point and does not get , namely str1[0]=‘a’,str1[3]=‘d’,str1[4]=‘e’,str1[5]=‘f’. Again , If you add step The parameter is negative , Represents slice from reverse . Positive direction first a The index subscript value is 0, the last one n The index subscript value is -1, The result is “nmlk”.
str1 = 'abcdefghijklmn'
print(str1[-1:-5:-1])
# nmlk
find() function
str1 = 'abcdefghijklmn'
num = str1.find('def')
print num
# 3
split() function
strip() function
>>> str1 = " I am a teacher "
>>> print(str1.strip())
I am a teacher
>>>
join() function
>>> num = ['I','am','a','teacher']
>>> sep = ' '
>>> str1 = sep.join(num)
>>> print str1
I am a teacher
>>>
in any case , The author hopes that this article can popularize some Python knowledge , I hope you can write code with me , Progress together . If the article can give you some trivial ideas and help with your research or project , It's even more gratifying . The author's biggest expectation is some stories in the article 、 word 、 Code or cases can help you , To those who struggle .
Words , The author passed the Python In fact, you can find some good jobs , But because I like teaching , Give up the Internet in Beijing , Choose to return to Guizhou , Become a college teacher . ha-ha , At that time, I wanted to go back to teach Python And big data knowledge , Although it's just a common choice , But I really hope I can stand in front of the podium , Keep your original mind , Teach more students 、 Popularize more Python Programming knowledge , Cultivate more data analysis for hometown 、 data mining 、 big data 、 Network security and other fields of talent , Make a modest contribution . Finally, the author left Beijing and chose to go back to Guizhou to teach :
Guizhou is a long way from zongmei ,
It's a bad time .
Three or four broken books were collected ,
I will teach you .
Last , Thank you for your attention “ Na Zhang's home ” official account , thank CSDN So many years of company , Will always insist on sharing , I hope your article can accompany me to grow up , I also hope to keep moving forward on the road of technology . If the article is helpful to you 、 Have an insight , It's the best reward for me , Let's see and cherish !2020 year 8 month 18 The official account established by Japan , Thank you again for your attention , Please help to promote it “ Na Zhang's home ”, ha-ha ~ Newly arrived , Please give me more advice .
regret , Let's understand perfection .
Pass away , Let's move on .
Her posture in the night is so beautiful .
(By: Na Zhang's home Eastmount 2020-08-22 Night in Wuhan https://blog.csdn.net/Eastmount)
The references are as follows :
[1] Author books 《Python Network data crawling and analysis from the beginning to proficient 》
[2] The author blog :https://blog.csdn.net/Eastmount
[3] Xu teacher blog :https://blog.csdn.net/xufive/article/details/102993570
[4] https://www.runoob.com/python