2017年9月30日 星期六

Python - Flow Control 筆記

控制流程Flow Control為程式語言重要的一環,在很多語言中都看得到控制流程,以下我要介紹python的控制流程

Python的布林值Boolean分別為True & False,boolean開頭都是大寫
True 成立
False 不成立

and:全為真才是真
or:任一為真即為真

> 大於 greater than
3>4 # False
4>3 # True

< 小於 less than
5<7 # True
6<4 # False

== 等於 equal
'3' == '3' # True
1 == 2 # False

!= 不等於 not equal
3 != 4 # True
3!= 3 # False

if判斷式
if a > b :
    print('a>b')
elif b > a :
    print('b>a')
else:
    print('a==b')

迴圈Loops,用於處理(迭代iterate)連續的資料sequence

For Loops

迭代串列
seq = [1, 2, 3, 4, 5]
for item in seq:
    print(item)

迭代字典
seq = {'Tom':'29', 'John':'30', 'Amy':'15'}
for key in seq:
    print(key) # 連續的key
    print(seq[key]) # 利用key找出value

迭代串列內容為Tuple
seq = [(1, 2), (3, 4), (5, 6)]

for (tu1, tu2) in seq: # 括號()可省略
    print (tu2)
    print(tu1)

while loops
while i<5:
    print(i)
    i = i +1

利用range()建立數字序列
range(start, stop, step)
備註:stop前停止
range(10) # 0..9
range(1, 10) # 1..9
range(1, 10 , 2) # 奇數1..9
應用
list(range(0, 7)) # [0 ,1 ,2 ,3 ,4, 5, 6]
list(range(0, 7, 2)) # [0, 2, 4, 6]
for i in range(0, 7):
    print(i) # 0 1 2 3 4 5 6

串列生成式
seq = [1, 2, 3, 4]
a = [num**2 for num in seq] # [1, 4, 9 ,16]

如果使用range的情況
a = [num**2 for num in range(1,5)] # [1, 4, 9 ,16]


沒有留言:

張貼留言