PYTHON 控制語句
阿新 • • 發佈:2022-11-29
1.1 if語句
1.1.1 if結構
if 條件:
程式碼塊
如果條件成立(True),則執行程式碼塊。
score = 100
if score >=90:
print("優秀")
1.1.2 if -else結構
if 條件:
程式碼塊1
else:
程式碼塊2
條件成立執行程式碼塊1,否則執行程式碼塊2
score = int(input("請輸入成績:"))
if score >= 60:
print("及格")
else:
print("不及格")
1.1.3 elif 結構
if 條件1: 程式碼塊1 elif 條件2: 程式碼塊2 elif 條件3: 程式碼塊3 …… elif 條件n: 程式碼塊n else: 程式碼塊n+1
從上到下,依次測試,如果哪個條件成立就執行哪個。 都不成立執行程式碼塊n+1
score = int(input("請輸入成績:"))
if score >= 90:
print("優秀")
elif score >= 70:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
1.2 三元運算
對於c語言: 條件 ? 表示式1:表示式2
#include <stdio.h> int main() { int score = 50; char *ps = score >=60 ? "及格":"不及格"; printf("%s\n",ps); return 0; }
相要實現相同的功能,python中用:
表示式1 if 條件 else 表示式2
score = 50
result = "及格" if score >= 60 else "不及格"
print(result)
1.3 match ... case結構
類似於c語言中的switch結構,但要強大的多。python 3.10中開始出現。
1.3.1 基本匹配
n = -1 match n: case 1: print("正數") case 0: print("0") case -1: print("負數") case _: print("錯誤")
n和匹配項對比,成立執行其中的程式碼,都不成功執行 _
的分支 ,類似switch中的default
1.3.2 匹配多個值(或)
同時匹配多個值
def match_test(status):
match status:
case 1 | 2 | 3: # status 是1,2,3都進入這個分支
return "正常結束"
case 4 | 5:
return "發生一些錯誤"
case _:
return "致命錯誤"
print(match_test(2))
1.3.3 列表匹配
在匹配中按最接近的匹配,同時可以進行賦值,元組同樣。
def match_test(status):
match status:
case [1, 2]:
return "1,2"
case [3, 4]:
return "3,4"
case [3, b]:
return b
case [a, b, c]:
return "->",a, b, c
case [a, b, *args]:
return a, b, *args
case _:
return "錯誤"
print(match_test([3, 3, 3]))
print(match_test([3, 3, 3]))
[1,2] 匹配第一個: case [1, 2]
[3,4] 匹配第二個:case [3, 4]
[3,5] 匹配第三個,同時把5賦值給b:case [3, b]
[3,3,3] 匹配第四個,同時賦值給a,b,c:case [a, b, c]
[3,4,5,6] 匹配第五個,同時賦值給a=3,b=4,args=[5,6]
子模式:匹配多個條件
def match_test(status):
match status:
# 匹配其中的一個單詞
case [('morning' | 'afternoon' | 'evening'), info]:
print("Good {0[0]}! {0[1]}".format(status))
case ['hello', 'abc']:
print("hello, abc!")
case _:
print("錯誤")
match_test(['morning', 'It is time to work!'])
match_test(['hello', 'abc'])
1.3.4 匹配物件屬性
class Circle:
def __init__(self, x, y, radius):
self.x = x
self.y = y
self.radius = radius
def match_test(circle):
match circle:
case Circle(x=1, y=1, radius=1):
print("標準大小")
case Circle(x=2, y=3, radius=4):
print("預設大小")
case _:
print("錯誤")
match_test(Circle(1, 1, 1))
1.3.5 在匹配中新增條件判斷
status = 1
flag = True
match status:
case 1 if flag:
print("1")
case 2:
print("2")
1.4 while迴圈
while 條件:
語句塊
continue # 結束本次迴圈,繼續執行下一次迴圈
break # 強制離開迴圈
else:
語句塊
當迴圈條件為False時執行else塊(就是正常結束),如果用break,異常,return強制結束則不行。
i = 0
while i < 10:
i += 1
print('*'*i)
else:
print("end")
1.5 for迴圈
for 迭代變數 in 序列: # 序列包括字串,列表,元組,集合等
語句塊
continue
break
else:
語句塊
當迴圈正常結束時執行else塊,如果用break,異常,return強制結束則不行。
for i in "hello world":
print(i)
else:
print("end")
a = [1,2,3,4,5,6]
for i in a[1:3]: # 迴圈列表區間內容
print(i)
1.5.1 迴圈range
生成數字序列:range(開始,結束,步長), 注意不包括結束位置
for i in range(5): # 0-5(不包括5)
print(i)
for i in range(0,100,2):
print(i)
1.5.2 迴圈enumerate物件
他會給列表元素新增一個序號,生成:序號 元素值
a = ["a", "b", "c", "d"]
for n, item in enumerate(a):
print(n, item)
1.5.3 九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print("{}×{}={:2d}".format(j,i,i*j), end="\t")
print()
輸出
1×1= 1
1×2= 2 2×2= 4
1×3= 3 2×3= 6 3×3= 9
1×4= 4 2×4= 8 3×4=12 4×4=16
1×5= 5 2×5=10 3×5=15 4×5=20 5×5=25
1×6= 6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7= 7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8= 8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9= 9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
1.6 pass語句
用於佔位,什麼也不做,當沒想好時可以這樣寫,防止報錯。
for i in range(1,10):
pass