📖研習進度


while loop

while 條件式:
    主程式區塊
else:               # 非必須
    後置程式區塊      # 非必須
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

  • breakcontinue敘述可放至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
n = 111
if n > 100:
  result = "success"
else:
  result = "failed"

print(result)
## success
result2 = "success" if n >100 else "failed"
print(result2)
## success
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 loop

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

  • 雖然for loop的運行並不需要索引,但有時仍需要使用索引來進行訪問
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]

tuple unpacking

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

Iterations與Comprehension

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'

list comprehensive

  • list comprehensive (列表推導) 可將⼀個for迴圈 (將list中的元素取出修改) 組成述句,壓縮為⼀⾏簡短易讀程式碼的簡單⽅法
  • 一般來說,list comprehensive執行速度會較for loop快(兩倍)
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/三月']

dict comprehensive

new_dict = { expr1: expr2 for variable in list if condition }
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}

Multiple Versus Single Pass Iterators

  • range 支援len與索引取值(indexing):
R = range(5)
len(R)
## 5
R[0]
## 0
  • range 支援 Multiple Iterators
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
  • 在Python 3.X中,zip , map 則『不』支援Multiple Iterators,為 Single Iterator:
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

dictionary view iterables

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

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運算式判斷


[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
## ''
['f', 't'][bool('')]
## 'f'
['f', 't'][bool('spam')]
## 't'