天天看點

Python基礎(四) | 程式控制結構

第四章 程式控制結構

⭐本專欄旨在對Python的基礎文法進行詳解,精煉地總結文法中的重點,詳解難點,面向零基礎及入門的學習者,通過專欄的學習可以熟練掌握python程式設計,同時為後續的資料分析,機器學習及深度學習的代碼能力打下堅實的基礎。

🔥本文已收錄于Python基礎系列專欄: Python基礎系列教程 歡迎訂閱,持續更新。

4.1 條件測試

Python基礎(四) | 程式控制結構

4.1.1 比較運算

a = 10
b = 8
print(a > b)     # 大于
print(a < b)     # 小于
print(a >= b)    # 大于等于
print(a <= b)    # 小于等于
print(a == b)    # 等于
print(a != b)    # 不等于      
True
False
True
False
False
True      
  • 非空
ls = [1]
if ls:            # 資料結構不為空、變量不為0、None、False 則條件成立
    print("非空")
else:
    print("空的")      
非空      

4.1.2 邏輯運算

  • 與、或、非
a = 10
b = 8
c = 12
print((a > b) and (b > c))    # 與
print((a > b) or (b > c))     # 或
print(not(a > b))             # 非      
False
True
False      
  • 複合邏輯運算的優先級 非 > 與 > 或
print(True or True and False)      
True      
print((True or True) and False)      
False      

4.1.3 存在運算

元素 in 清單/字元串

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]      
print("BMW" in cars)
print("BENZ" in cars)      
True
False      

元素 not in 清單/字元串

print("BMW" not in cars)
print("BENZ" not in cars)      
False
True      

4.2 分支結構——if語句

Python基礎(四) | 程式控制結構

4.2.1 單分支

模闆 注意有“:”

if 條件:   縮進的代碼塊

age = 8
if age > 7:
    print("孩子,你該上學啦!")      
孩子,你該上學啦!      

4.2.2 二分支

模闆 if 條件:   縮進的代碼塊 else:   縮進的代碼塊

age = 6
if age > 7:
    print("孩子,你該上學啦!")
else:
    print("再玩兩年泥巴!")      
再玩兩年泥巴!      

4.2.3 多分支

模闆 if 條件:   縮進的代碼塊 elif 條件:   縮進的代碼塊 elif 條件:   縮進的代碼塊 ... else:   縮進的代碼塊

age = 38
if age < 7:
    print("再玩兩年泥巴")
elif age < 13:
    print("孩子,你該上國小啦")
elif age < 16:
    print("孩子,你該上國中了")
elif age < 19:
    print("孩子,你該上高中了")
elif age < 23:
    print("大學生活快樂")
elif age < 60:
    print("辛苦了,各行各業的工作者們")
else:     # 有時為了清楚,也可以寫成elif age >= 60:
    print("享受退休生活吧")      
辛苦了,各行各業的工作者們      

不管多少分支,最後隻執行一個分支

4.2.4 嵌套語句

題目:年滿18周歲,在非公共場合方可抽煙,判斷某種情形下是否可以抽煙

age = eval(input("請輸入年齡"))
if age > 18:
    is_public_place = bool(eval(input("公共場合請輸入1,非公共場合請輸入0")))
    print(is_public_place)
    if not is_public_place:
        print("可以抽煙")
    else:
        print("禁止抽煙")        
else:
    print("禁止抽煙")      
請輸入年齡19
公共場合請輸入1,非公共場合請輸入01
True
禁止抽煙      

4.3 周遊循環——for 循環

4.3.1 主要形式

  • for元素in可疊代對象: 執行語句

4.3.2 執行過程

  • 從可疊代對象中,依次取出每一個元素,并進行相應的操作

1、直接疊代——清單[ ]、元組( )、集合{ }、字元串" "

graduates = ("李雷", "韓梅梅", "Jim")
for graduate in graduates:
    print("Congratulations, "+graduate)      
Congratulations, 李雷
Congratulations, 韓梅梅
Congratulations, Jim      

2、變換疊代——字典

students = {201901: '小明', 201902: '小紅', 201903: '小強'}
for k, v in students.items():
    print(k, v)
for student in students.keys():
#for student in students 同樣是疊代鍵key
    print(student)      
201901 小明
201902 小紅
201903 小強
201901
201902
201903      

3、range()對象

res=[]
for i in range(10000):
    res.append(i**2)
print(res[:5])
print(res[-1])      
[0, 1, 4, 9, 16]
99980001      
res = []
for i in range(1, 10, 2):
    res.append(i ** 2)
print(res)      
[1, 9, 25, 49, 81]      

4.3.3 循環控制:break 和 continue

  • break 結束整個循環
product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82] # 1組10個産品的性能評分
 # 如果低于75分的超過1個,則該組産品不合格
i = 0
for score in product_scores:
    if score < 75:
        i += 1 
    if i == 2:
        print("産品抽檢不合格")
        break      
産品抽檢不合格      
  • continue 結束本次循環
product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82] # 1組10個産品的性能評分
 # 如果低于75分,輸出警示
print(len(product_scores))
for i in range(len(product_scores)):
    if product_scores[i] >= 75:
        continue 
    print("第{0}個産品,分數為{1},不合格".format(i, product_scores[i]))      
10
第3個産品,分數為70,不合格
第4個産品,分數為67,不合格      

4.3.4 for 與 else的配合

如果for 循環全部執行完畢,沒有被break中止,則運作else塊

product_scores = [89, 90, 99, 70, 67, 78, 85, 92, 77, 82] # 1組10個産品的性能評分
 # 如果低于75分的超過1個,則該組産品不合格
i = 0
for score in product_scores:
    if score < 75:
        i+=1 
    if i == 2:
        print("産品抽檢不合格")
        break
else:
    print("産品抽檢合格")      
産品抽檢不合格      

4.4 無限循環——while 循環

Python基礎(四) | 程式控制結構

4.4.1 為什麼要用while 循環

  • 經典題目:猜數字
albert_age = 18
#第1次
guess = int(input(">>:"))
if guess > albert_age :
    print("猜的太大了")
elif guess < albert_age :
    print("猜的太小了")
else:
    print("猜對了")
#第2次
guess = int(input(">>:"))
if guess > albert_age :
    print("猜的太大了")
elif guess < albert_age :
    print("猜的太小了")
else:
    print("猜對了")      

代碼可能需要重複執行,可是又不知道具體要執行多少次

4.4.2 while循環的一般形式

主要形式:

  • while判斷條件: 執行語句 條件為真,執行語句 條件為假,while 循環結束
albert_age = 18 
guess = int(input(">>:"))
while guess != albert_age: 
    if guess > albert_age :
        print("猜的太大了.")
    elif guess < albert_age :
        print("猜的太小了")
    guess = int(input(">>:"))
print("猜對了")      
>>:20
猜的太大了.
>>:18
猜對了      

4.4.3 while與風向标

albert_age = 18 
flag = True     # 布爾類型
while flag:
    guess = int(input(">>:"))
    if guess > albert_age :
        print("猜的太大了")
    elif guess < albert_age :
        print("猜的太小了")
    else:
        print("猜對了")
        flag = False      
flag=True  
while flag:  
    pass  
    while flag:  
        pass  
        while flag:     
            flag=False     # 循環逐層判斷,當flag為false時,循環會逐層退出      

4.4.4 while 與循環控制 break、continue

albert_age = 18 
while True:
    guess = int(input(">>:"))
    if guess > albert_age :
        print("猜的太大了")
    elif guess < albert_age :
        print("猜的太小了")
    else:
        print("猜對了...")
        break    # 當訴求得到滿足,就跳出循環      

輸出10以内的奇數

i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue       # 跳出本次循環,進入下一次循環
    print(i)      
1
3
5
7
9      

4.4.5 while與else

如果while 循環全部執行完畢,沒有被break中止,而是條件不再滿足了而中止,則運作else塊

count = 0
while count <= 5 :
    count += 1
    print("Loop",count)
else:
    print("循環正常執行完啦")      
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦      

4.4.6 再看兩個例子

應用:删除清單中的特定值

pets = ["dog", "cat", "dog", "pig", "goldfish", "rabbit", "cat"]      
while "cat" in pets:
    pets.remove("cat")
pets      
['dog', 'dog', 'pig', 'goldfish', 'rabbit']      

應用:将未讀書籍清單中書名分别輸出後,存入已讀書籍清單

not_read = ["紅樓夢", "水浒傳", "三國演義", "西遊記"]
have_read = []
while not_read:     # not_read非空,循環繼續,否則中止
    book = not_read.pop()
    have_read.append(book)
    print("我已經讀過《{}》了".format(book))
print(not_read)
print(have_read)      
我已經讀過《西遊記》了
我已經讀過《三國演義》了
我已經讀過《水浒傳》了
我已經讀過《紅樓夢》了
[]
['西遊記', '三國演義', '水浒傳', '紅樓夢']      

4.5 控制語句注意問題

Python基礎(四) | 程式控制結構

4.5.1 盡可能減少多層嵌套

  • 可讀性差,容易把人搞瘋掉
if 條件:
    執行語句
    if 條件:
        執行語句
        if...      

4.5.2 避免死循環

條件一直成立,循環永無止境

# while True:
    # print("歡迎訂閱專欄")      

4.5.3 封裝過于複雜的判斷條件

如果條件判斷裡的表達式過于複雜

出現了太多的 not/and/or等

a, b, c, d, e = 10, 8, 6, 2, 0
if (a > b) and (c >d) and (not e):
    print("過于複雜")      
numbers = (10, 8, 6, 2, 0)


def judge(num):
    a, b, c, d, e = num
    x = a > b
    y = c > d
    z = not e
    return x and y and z


if judge(numbers):
    print("簡潔明了")