📖研習進度
while loopwhile 條件式:
主程式區塊
else: # 非必須
後置程式區塊 # 非必須
條件式:布林運算式,其結果為True或是Falese
只要條件式為True,主程式區塊就會反覆執行
當條件式為False時,while迴圈會執行後置程式區塊,然後終止
n = 9
r = 1
while n > 0:
r = r * n
n = n - 1
else:
print("後置程式區塊執行完畢,", "且 n =", n, "。")
## 後置程式區塊執行完畢, 且 n = 0 。
x = 'NCCU'
while x:
print(x, end = '\n')
x = x[1:]
## NCCU
## CCU
## CU
## U
a = 0; b = 10
while a < b: # One way to code counter loops
print(a, end=' ')
a += 1
## 0 1 2 3 4 5 6 7 8 9
break與continue敘述可放至while loop之中
如執行break,則立即終止while loop,且不執行後置程式區塊。因為當break中斷while loop時,while條件式仍為True
如執行continue,則會跳過continue後面的程式碼,回到while條件式繼續執行下一個loop
if-elif-else判斷式if 條件式1:
程式區塊1
elif 條件式2:
程式區塊2
elif 條件式3:
程式區塊3
.....
.....
elif 條件式(n-1):
程式區塊(n-1)
else:
程式區塊n
條件式1為True,則會執行程式區塊1;否則,條件式2為True,則會執行程式區塊2,依此類推,直到找到一個條件式為True為止。
若沒有條件式為True時,則會執行else子句的程式區塊n
視使用情況,elif與else子句非必須,可省略。
n = 111
if n > 100:
result = "success"
else:
result = "failed"
print(result)
## success
result2 = "success" if n >100 else "failed"
print(result2)
## success
pass敘述來佔位以滿足要求x = 10
if x < 5:
pass
else:
x = 5
print(x)
## 5
choice = "ham"
if choice == "spam":
print(1.25)
elif choice == "ham":
print(1.99)
elif choice == "eggs":
print(0.99)
elif choice == "bacon":
print(1.10)
else:
print("Bad choice")
## 1.99
choice = "ham"
print({"spam": 1.25,
"ham": 1.99,
"eggs": 0.99,
"bacon": 1.1}[choice])
## 1.99
branch = { "spam": 1.25,
"ham": 1.99,
"eggs": 0.99,
"bacon": 1.1}
branch.get("ham", "Bad choice")
## 1.99
branch.get("HAM", "Bad choice")
## 'Bad choice'
choice = "HAM"
try:
print(branch[choice])
except KeyError:
print("Bad choice")
## Bad choice
if choice in branch:
print(branch[choice])
else:
print("Bad choice")
## Bad choice
for loopPython的for loop不需要指定索引,而是直接對可迭代物件的元素逐一取出來做處理
可迭代物件包含:list, tuple, set, str, generator, enumerate()等
for item in 可迭代物件:
主體程式區塊
else:
後置程式區塊
nums = [60, 70, 200, 80, 90]
for n in nums:
print(n)
if n > 100:
print("There is a number bigger than 100")
break
else:
print("Not found!")
## 60
## 70
## 200
## There is a number bigger than 100
range()x = [1, 2, 4, -7, 19, -4, 7]
for i in range(len(x)):
if x[i] < 0:
print("找到負數",x[i], ",其索引值為", i)
## 找到負數 -7 ,其索引值為 3
## 找到負數 -4 ,其索引值為 5
range(1, 11)
## range(1, 11)
type(range(1, 11))
## <class 'range'>
list(range(1, 11))
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(10, 1))
## []
list(range(10, 1, -1))
## [10, 9, 8, 7, 6, 5, 4, 3, 2]
somelist = [(1, 2), (3, 7), (9, 5), (10, 4)]
result = 0
for item in somelist:
result = result + (item[0] * item[1])
print(result)
## 2
## 23
## 68
## 108
enumerate()x = ["a", "b", "x"]
enumerate(x)
## <enumerate object at 0x7fd455cb81c0>
list(enumerate(x))
## [(0, 'a'), (1, 'b'), (2, 'x')]
x = [1, 3, -1, 4, 5, -9, 7]
for i, n in enumerate(x):
if n < 0:
print("找到負數,", "其索引值為", i)
## 找到負數, 其索引值為 2
## 找到負數, 其索引值為 5
zip()L1 = [1,2,3,4]
L2 = [5,6,7,8]
zip(L1, L2)
## <zip object at 0x7fd455cb9700>
list(zip(L1, L2))
## [(1, 5), (2, 6), (3, 7), (4, 8)]
for (x, y) in zip(L1, L2):
print(x, "+" , y, '-->', x+y)
## 1 + 5 --> 6
## 2 + 6 --> 8
## 3 + 7 --> 10
## 4 + 8 --> 12
T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
T3
## (7, 8, 9)
list(zip(T1, T2, T3))
## [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
S1 = 'abc'
S2 = 'xyz123'
list(zip(S1, S2)) # # Truncates at len(shortest)
## [('a', 'x'), ('b', 'y'), ('c', 'z')]
Python針對常見的『循環』另外提供更方便也更有效率的觀念與工具:
Iterable object (可迭代物件) ==> __ iter __
Iterator object (迭代器物件) ==> __ next __
L = [1, 2, 3]
I = iter(L) # Obtain an iterator object from an iterable
I.__next__()
## 1
I.__next__()
## 2
I.__next__()
# I.__next__()
# StopIteration:
#
# Detailed traceback:
# File "<string>", line 1, in <module>
## 3
L = [1, 2, 3]
iter(L) is L
# L.__next__()
# AttributeError: 'list' object has no attribute '__next__'
## False
I = iter(L)
I.__next__()
## 1
next(I) # Same as I.__next__()
## 2
L = [1, 2, 3]
for X in L: # Automatic iteration
print(X ** 2, end = ' ') # Obtains iter, calls __next__, catches exceptions
## 1 4 9
L = [1, 2, 3]
I = iter(L) # Manual iteration: what for loops usually do
while True:
try: # try statement catches exceptions
X = next(I)
except StopIteration:
break
print(X ** 2, end=' ')
## 1 4 9
D = {'a':1, 'b':2, 'c':3}
for key in D.keys():
print(key, D[key])
## a 1
## b 2
## c 3
D = {'a':1, 'b':2, 'c':3}
I = iter(D)
I.__next__()
## 'a'
next(I)
## 'b'
next(I)
# next(I)
# StopIteration:
#
# Detailed traceback:
# File "<string>", line 1, in <module>
## 'c'
L = [1, 2, 3, 4, 5]
for i in range(len(L)):
L[i] += 10
L
## [11, 12, 13, 14, 15]
L = [1, 2, 3, 4, 5]
L = [x + 10 for x in L]
L
## [11, 12, 13, 14, 15]
L = [1, 2, 3, 4, 5]
L = [x ** 2 for x in L if x % 2 == 0]
L
## [4, 16]
res = []
for x in ['2020', '2021']:
for y in ['/一月', '/二月', '/三月']:
res.append(x + y)
res
## ['2020/一月', '2020/二月', '2020/三月', '2021/一月', '2021/二月', '2021/三月']
res = [x + y for x in ['2020', '2021'] for y in ['/一月', '/二月', '/三月']]
res
## ['2020/一月', '2020/二月', '2020/三月', '2021/一月', '2021/二月', '2021/三月']
x = [1, 2, 3, 4]
x_squared_dict = {item: item * item for item in x}
x_squared_dict
## {1: 1, 2: 4, 3: 9, 4: 16}
R = range(5)
len(R)
## 5
R[0]
## 0
R = range(3) # range allows multiple iterators
# next(R)
# TypeError: 'range' object is not an iterator
I1 = iter(R)
next(I1)
## 0
next(I1)
## 1
I2 = iter(R)
next(I2)
## 0
next(I2)
## 1
Z = zip((1, 2, 3), (10, 20, 30))
I1 = iter(Z)
I2 = iter(Z)
next(I1)
## (1, 10)
next(I1)
## (2, 20)
next(I2)
## (3, 30)
M = map(abs, (-1, 0, 1))
I1 = iter(M)
I2 = iter(M)
print(next(I1), next(I1), next(I1))
# next(I2)
# StopIteration:
## 1 0 1
R = range(3)
I1, I2 = iter(R), iter(R)
[next(I1), next(I1), next(I1)]
## [0, 1, 2]
next(I2)
## 0
D = {'a': 1, 'b': 2, 'c': 3}
D
## {'a': 1, 'b': 2, 'c': 3}
K = D.keys()
K
# next(K) # K are not iterators themselves
# TypeError: 'dict_keys' object is not an iterator
## dict_keys(['a', 'b', 'c'])
I = iter(K)
next(I)
## 'a'
next(I)
## 'b'
for k in D.keys(): print(k, end=' ')
## a b c
產生器(Generator)的語法類似list comprehension,差別只在於使用()替代[]
可透過for loop來存取
使用產生器可不需立即在記憶體中儲存全部資料,可處理大型數據資料
x = [1, 2, 3, 4]
x_square = (item * item for item in x)
type(x_square)
## <class 'generator'>
for square in x_square:
print(square, end=" ")
## 1 4 9 16
bool運算式判斷數字0, 0.0與0 + 0j均為False,其他數字皆為True
空字串""為False,其他字串皆為True
空list[],空tuple()與空字典{}皆為False
None為False
Short-circuit Evaluation:and與or並不會回傳運算後的布林值,而是會回傳物件。
[2] and [3, 4]
## [3, 4]
[] and [3, 4]
## []
[2] or [3, 4]
## [2]
[] or [3, 4]
## [3, 4]
x = []
if x and myfun():
pass
x = 0
x <= 0 and print("x <= 0")
## x <= 0
x and 1/x
# 1/x
## 0
x and 1/x # 當x為0時,則1/x不會執行
## 0
2 and 3, 3 and 2
## (3, 2)
[] and {}
## []
3 and []
## []
2 or 3
## 2
3 or 2
## 3
[] or 3
## 3
[] or {}
## {}
X = "A" and '' and "C" and None
X
## ''
bool其他範例['f', 't'][bool('')]
## 'f'
['f', 't'][bool('spam')]
## 't'