[Python from zero to one] 2. Conditional statement, loop statement and function of syntax basis

Eastmount 2020-11-13 00:01:04
python zero conditional statement loop

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 .

One . Conditional statements

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 .

1. Single branch

The single branch grammar is as follows :

if <condition>:

< 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')

The output is as follows :
 Insert picture description here

2. Two branches

The two branch grammar is as follows :

if <condition>:

The execution process is shown in the figure below :

 Insert picture description here

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(' Variable a Less than 5')

The output is as follows , Because of the variable a by 10, Greater than 5 perform if The statement in .

 Insert picture description here

3. Multiple branches

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>
<case2 statements>
<case3 statements>
<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)
if num >= 90:
print('A Class')
elif num >= 80:
print('B Class')
elif num >= 70:
print('C Class')
elif num >=60:
print('D Class')
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 .

 Insert picture description here

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 :

  • Use or ( or ), It means that if one of the two conditions is true, the judgment condition is successful
  • Use and ( And ), When only two conditions hold at the same time , It's only when you judge the conditions that you succeed
# Judge whether the value is less than 0 Or greater than 10
num = 10
if num < 0 or num > 10:
# 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):

The output result is shown in the figure below :

 Insert picture description here

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 ")

Two . Loop statement

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 .

1.while loop

while The basic format of a loop statement is as follows :

while <condition>:

The execution process is shown in the figure below :

 Insert picture description here

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
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 .

 Insert picture description here

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
while i<5:
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 .

 Insert picture description here

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 .

 Insert picture description here

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 :

 Insert picture description here

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 
# Output results 

The output is as follows :

[8, 42, 12]
[3, 5, 37]

2.for loop

for The basic format of a loop statement is as follows :

for <var> in <sequence>:

The flow chart is as follows :

 Insert picture description here

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('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):

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 .

 Insert picture description here

3.Break、Continue and Pass sentence

Break and Continue Are two common out of loop statements .

  • Break sentence
    Jump out of the inner layer while、for loop , Terminate loop during block execution , And out of the loop .
s = 0
num = 0
while num<20:
num += 1
s += num
if s > 100:
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.

  • Continue sentence
    Terminate the current loop during block execution , Jump out of the cycle , Execute next cycle .
for num in range(10):
if num % 2 == 0:
print("even 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

  • pass sentence
    pass A statement is an empty statement , In order to maintain the integrity of the program structure .
# Output Python Every letter of 
for letter in 'Python':
if letter == 'h':
print(' This is a pass block ')
print(' The current letter :', letter)
print("Good bye!")

The output result is shown in the figure below :

 Insert picture description here

4. Nested loop

while The basic grammar is as follows :

while expression:
while expression:

for The basic grammar is as follows :

for iterating_var in sequence:
for iterating_var in sequence:

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 :

  • Compare two adjacent elements , And then put the larger elements in the back ( Forward order ), After a round of comparison, the largest element is placed in the last position , Like fish in the water spit bubbles in the rising process of growing .
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 :

 Insert picture description here

You may wonder bubble_sort() What is it? ? It's actually a custom function , Let's talk about .

3、 ... and . function

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. Custom function

(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]):
[return value1,value2...valueN]

among :

  • Defining functions requires the use of def key word
  • function_name Represents the function name , The colon on the back (:) Don't forget it , And indent
  • [para1,para2…paraN] Said parameters , It can be omitted , You can also have multiple parameters
  • [return value1,value2…valueN] Represents the return value , There can be no return value , You can also have multiple return values
  • It should be noted that custom functions have return values , The main function needs to accept the returned result

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):
c = a + b
print('sum =',c)
# Function call 
# 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):
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)

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):
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.

 Insert picture description here

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 .

2. Common internal library functions

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 :

 Insert picture description here

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
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 .

 Insert picture description here

3. Third party library functions

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 :

  • module_name.method(parametes)

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 .

 Insert picture description here

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 .

Four . summary

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 .

 Insert picture description here

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


  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database