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 CSDN The article , Links are as follows :
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 .
Before we talk about conditional sentences , You need to supplement the knowledge of sentence blocks first . A statement block is not a statement , It is a set of statements that are executed once or more than once when the condition is true , Place a space indent in front of the code to create a block of statements . It is similar to C、C++、Java The curly braces of other languages ({ }) To indicate the beginning and end of a statement block .
stay Python Use a colon in (:) To identify the beginning of a block of statements , Each statement in the block is indented and indented by the same amount , When you go back to the previous level of indentation , It means that the current statement block has ended . Let's start with a detailed explanation of conditional statements .
The single branch grammar is as follows :
if <condition>:
<statement>
<statement>
< condition > Is a conditional expression , The basic format is < expr >< relop >< expr >;< statement > It's the body of the sentence . If the condition is true (True) Just execute the statement , If it is false (False) Just skip the statement , Execute the next statement . Conditional judgments usually have Boolean expressions (True、False)、 Relationship expression (>、<、>=、<=、= =、!=) And logical expressions (and、or、not, The priority from high to low is not、and、or) etc. .
Be careful : stay Python2.x In the version , Conditional expressions are not required to be enclosed in brackets , But the conditional expression must be followed by an English colon character .
a = 10
if a==10:
print(' Variable a be equal to 10')
print(a)
The output is as follows :
The two branch grammar is as follows :
if <condition>:
<statement>
<statement>
else:
<statement>
<statement>
The execution process is shown in the figure below :
If the conditional statement < condition > It's true ,if The following statement is executed , If it is false , execute else The following block of statements . The format of the conditional statement is :< expr >< relop >< expr >, among < expr > Expression for 、 For relational operators . for example :a >= 10、b != 5 etc. .
a = 10
if a >= 5:
print(' Variable a Greater than or equal to 5')
print(a)
else:
print(' Variable a Less than 5')
print(a)
The output is as follows , Because of the variable a by 10, Greater than 5 perform if The statement in .
if Many branches are made up of if-elif-else form , among elif amount to else if, At the same time, it can use multiple if Nesting of . The specific grammar is as follows :
if <condition1>:
<case1 statements>
elif<condition2>:
<case2 statements>
elif<condition3>:
<case3 statements>
...
else:
<default statements>
The statement evaluates each condition sequentially , If the current condition branch is True, Then execute the statement block under the corresponding branch , If nothing holds , execute else Statement block in , among else It can be omitted . The code is as follows :
num = input("please input:")
num = int(num)
print(num)
if num >= 90:
print('A Class')
elif num >= 80:
print('B Class')
elif num >= 70:
print('C Class')
elif num >=60:
print('D Class')
else:
print('No Pass')
The output value is 76, It's in 80 To 70 Between , The result is C Grade , The output result is shown in the figure below .
Be careful : because Python I won't support it switch sentence , So multiple conditional judgments , Only use elif To achieve , If multiple conditions need to be judged at the same time , Sure :
# Judge whether the value is less than 0 Or greater than 10
num = 10
if num < 0 or num > 10:
print('hello')
else:
print('undefine')
# Output results : undefine
# Judge whether the value is 0~5 perhaps 10~15 Between
num = 8
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):
print('hello')
else:
print('undefine')
The output result is shown in the figure below :
When if When there are multiple conditions, brackets can be used to distinguish the order of judgment , The judgment in brackets takes precedence , Besides and and or Priority is lower than >( Greater than )、<( Less than ) Wait for the judgment sign , That is, greater than and less than in the absence of parentheses will take precedence over and or .
meanwhile , You can also use... On the same line if Conditional statements , The following example . But we don't see people using similar grammar , In our writing projects or actual combat , It's likely that your code will be learned by others , Sometimes you're only responsible for part of it , Good code format and comments are very necessary .
var = 520
if (var ==520): print(" Thank you for your attention AI Safe house ")
Python Loop statements are mainly divided into while Circulation and for loop , It allows us to execute a statement or group of statements more than once .
while The basic format of a loop statement is as follows :
while <condition>:
<statement>
else:
<statement>
The execution process is shown in the figure below :
Conditional expression < condition > If it's true , Then the loop body repeats , Until the condition is false , The loop ends , If the condition is false the first time , Then jump out of the loop else sentence , Be careful else Sentences can be omitted , And a colon (:) Start to enter the loop , Indenting distinguishes blocks of statements . Conditional statements condition Including Boolean expressions (True、False)、 Relationship expression (>、<、>=、<=、= =、!=) And logical expressions (and、or、not) etc. .
Case study 1:1+2+…+100
i = 1
s = 0
while i <= 100:
s = s+i
i = i+1
else:
print('over')
print('sum = ', s)
This code is when the author writes a blog or lectures , Tell me about the most common examples of loop statements , seek 1+2+3+…+100 Result , The answer is 5050. This code is executed repeatedly “i<=100” Judge , When i Add to 101 when , Judge i>100 If it is false, the loop will end else sentence .
Case study 2: Loop through the web site
Take another example , By defining a while loop , call webbrowser Library open_new_tab() Function loop to open Baidu home page URL , The following code repeatedly opened Baidu home page 5 Time . The complete code is as follows :
import webbrowser as web
import time
import os
i=0
while i<5:
web.open_new_tab('http://www.baidu.com')
i=i+1
time.sleep(0.8)
else:
os.system('taskkill /F /IM iexplore.exe')
print('close IE')
The code is to call webbrowser In the library open_new_tab() Function to open the window ( Baidu links )5 Time .
Finally, the loop ends execution os.system() Operating system functions , call taskkill The order is over IE Browser process (Iexplore.exe), Other browser programs are modified to chrome.exe、qq.exe or firefox.exe that will do . The parameter “/F” Means to terminate a program by force ,“/IM” Represents an image , As shown in the figure below .
Be careful : The above code implements a loop to open a website , It can be used to swipe page views or Web Development test and other functions . For example, Sina blog and other parts of the page open a browser, accounting for the number of visits , You can cycle through the above code to increase the amount of reading , Some websites are sorted by the number of visitors , Try it . The author introduces this code only for readers to understand the loop , Also for the reptile knowledge behind the foreshadowing .
Case study 3: Odd and even numbers
Finally, a case of odd and even number calculation is added , The basic process is shown in the figure below :
The code is as follows :
numbers = [12, 37, 5, 42, 8, 3]
even = []
odd = []
while len(numbers) > 0:
number = numbers.pop()
if(number % 2 == 0): # Even number judgment
even.append(number)
else:
odd.append(number)
# Output results
print(even)
print(odd)
The output is as follows :
[8, 42, 12]
[3, 5, 37]
for The basic format of a loop statement is as follows :
for <var> in <sequence>:
<statement>
<statement>
The flow chart is as follows :
Custom loop variable var Traverse sequence Every value in the sequence , A block of statements that execute a loop once per value .sequences Represents a sequence , Common types are list( list )、tuple( Tuples )、strings( character string ) and files( file ). The following code is to calculate 1 To 100 Sum of , An example of outputting a triangle asterisk .
# Tuple loop
tup = (1,2,3,4,5)
for n in tup:
print(n)
else:
print('End for\n')
# Calculation 1+2+...+100
s = 0
for i in range(101):
s = s + i
print('sum =', s)
# Output triangle asterisk
for i in range(10):
print("*"*i)
The output result is shown in the figure below , Cycle through the epoch group tup Values in variables , Get and output in turn ; And then calculate 1 Add up to 100,range(101) Means to obtain in turn 101 Within the scope of 100 A digital , The cumulative result is 5050; Finally, the asterisk triangle is output ,print “ * ” * i In the code , The first asterisk represents the output asterisk string , The second asterisk is multiplication , Indicative output 5 asterisk , The final output triangle . Printing graphics is the basis of programming , Use Python Realization is better than C Language is much easier , But the principle logic is the same .
Break and Continue Are two common out of loop statements .
s = 0
num = 0
while num<20:
num += 1
s += num
if s > 100:
break
print("The sum is", s)
# The sum is 105
When the summation variable s Greater than 100 When , Get into if Judge , perform break Out of the loop , The final output 105.
for num in range(10):
if num % 2 == 0:
print("even number:", num)
continue
print("number:",num)
The output is as follows , When it's even continue Jump out of current loop ,for Only even numbers are output in the loop .
>>>
even number: 0
number: 1
even number: 2
number: 3
even number: 4
number: 5
even number: 6
number: 7
even number: 8
number: 9
>>>
# Output Python Every letter of
for letter in 'Python':
if letter == 'h':
pass
print(' This is a pass block ')
print(' The current letter :', letter)
print("Good bye!")
The output result is shown in the figure below :
while The basic grammar is as follows :
while expression:
while expression:
statement(s)
statement(s)
for The basic grammar is as follows :
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The following is the simplest bubble sort algorithm to supplement loop nesting knowledge . Bubble sort is the most common sort algorithm , It's also a very basic sort algorithm . Its realization idea is :
def bubble_sort(list):
count = len(list)
for i in range(count):
for j in range(i + 1, count):
if list[i] > list[j]:
list[i], list[j] = list[j], list[i]
return list
# Sorting algorithm
list = [3, 91, 23, 14, 56, 9]
print(" Before ordering :", list)
res = bubble_sort(list)
print(" After ordering :", res)
The output is as follows :
You may wonder bubble_sort() What is it? ? It's actually a custom function , Let's talk about .
When the reader needs to complete a block of statements for a specific function , You need to call the function to complete the corresponding function . Functions are divided into parametric functions and parametric functions , When a function provides different parameters , It can process different data . Now from the custom function 、 System function 、 Third party library functions are explained in three aspects .
(1) Define methods
To simplify programming , Improve code reusability , You can customize functions , The function is defined as follows :
def funtion_name([para1,para2...paraN]):
statement1
statement2
....
[return value1,value2...valueN]
among :
When a function is called , Formal parameters are given real parameters , Then execute the function body , And return the result at the end of the call .Return Statement to exit a function and return to where the function was called , The return value is passed to the caller .
First, let's look at a summation function with no return value fun1(), The code is as follows :
# Function definition
def fun1(a,b):
print(a,b)
c = a + b
print('sum =',c)
# Function call
fun1(3,4)
# 3 4
# sum = 7
Let's look at a calculator function that contains multiple parameters fun2(), The code is as follows ,return Return five results .
# Function definition
def fun2(a,b):
print(a,b)
X = a + b
Y = a - b
Z = a * b
M = a / b
N = a ** b
return X,Y,Z,M,N
# Function call
a,b,c,d,e = fun2(4,3)
print('the result are ',a,b,c,d,e)
re = fun2(2,10)
print(re)
The output is as follows , Return to addition in turn 、 Subtraction 、 Multiplication 、 division 、 Power operation result .
>>>
4 3
the result are 7 1 12 1.3333333333333333 64
2 10
(12, -8, 20, 0.2, 1024)
>>>
(2) Custom function parameters contain predefined
The default value is based on the custom function , Assign predefined values to some parameters . for example :
def fun3(a,b,c=10):
print(a,b,c)
n = a + b + c
return n
print('result1 =',fun3(2,3))
print('result2 =',fun3(2,3,5))
First call a by 2,b by 3,c For predefined values 10, Sum output 15; The second call modifies the predefined values c, The assignment is 5, To sum is to 2+3+5=10.
Be careful : A predefined value parameter cannot precede a parameter without a predefined value ; meanwhile , When a function is called , One to one assignment is recommended , You can also give specific parameters in the function call to assign values , But it should be noted that during the function call ( When using functions ), Parameters with predefined values cannot be assigned before parameters without predefined values .
Python The system provides some library functions for you to use , Here are the four most common library functions , namely str String library function 、math Database functions 、os Operating system library functions 、socket Network socket library function .Python Common internal library functions are as follows :
The following code is the specific usage of these four common internal library functions , The code is as follows :
# -*- coding:utf-8 -*-
# String library function
str1 = "hello world"
print(' Calculate string length :', len(str1))
str2 = str1.title()
print(' Conversion of the first letter to uppercase title :', str2)
str3 = '12ab34ab56ab78ab'
print(' String substitution :', str3.replace('ab',' '))
# Math library functions
import math
print(math.pi)
num1 = math.cos(math.pi/3)
print(' Cosine law :', num1)
num2 = pow(2,10)
print(' Power operation :', num2)
num3 = math.log10(1000)
print(' Seeking for 10 Log base :', num3)
# Operating system library functions
import os
print(' Output the currently used platform :', os.name)
path = os.getcwd()
print(' Get the current working directory ', path)
os.system('taskkill /F /IM iexplore.exe') # Close browser process
# Network socket library function
import socket
ip = socket.gethostbyname('www.baidu.com')
print(' Get Baidu ip Address ', ip)
The output result is shown in the figure below .
Python As an open source language , It supports a variety of open source libraries provided by third parties for our use . When using the third-party function library, the specific format is :
Express “ Third party function name . Method ( Parameters )”. for example httplib\httplib2 The library is for HTTP and HTTPS The client protocol of , Use httplib2 Before the library function , If not installed httplib2 The library will report an error “ImportError: No module named httplib2”, Pictured 2.18 Shown .
stay Linux Environment , Enter the command “easy_install httplib2” Can achieve automatic installation of expansion pack ,Windows Installation required in environment pip or easy_install Tools , Then call the command to execute the installation . The following article will explain pip Installation tools and usage , The following sections will also introduce various third-party library functions to achieve data crawling and analysis operations .
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 .
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-09-09 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] https://www.runoob.com/python/python-if-statement.html