TKU STAT × Python Basic

Loop & Conditional judgment


Kristen Chan

Agenda


  • 流程控制 (Conditional judgment)
  • 迴圈 (Loops)
    • for
    • while
    • Nested loops
  • 迴圈與流程控制結合應用 (Loops & Conditional judgment)
  • 進階迴圈 (Loops II)
    • break
    • continue

Conditional judgment

Conditional judgment


語法 ( if/elif/else )

if expression1:
    statement  #滿足條件一,要做的事
elif expression2:
    statement  #滿足條件二,要做的事
elif expression3:
    statement  #滿足條件三,要做的事 
else:
    statement  #上述條件皆不滿足,要做的事

Conditional judgment


Note : Python 程式結構與語法

註解

  • 單行註解
    # comments
    
  • 多行註解
    '''
    comments
    '''
    

Conditional judgment


Note : Python 程式結構與語法

延續多行

  • 程式太長換行
    print(\
      "Hello Python!!" \
    )
    

Conditional judgment


Note : Python 程式結構與語法

縮排

  • 利用 tab 或 4 個空白
    x = 3
    if x >3 :
      print('x 大於 3')
    else :
      print('x 小於 3')
    

Conditional judgment


利用 判斷式 if/elif/else 做出判斷

  • 若某件事為真 ( True ) ,則做出對應動作。
  • if 是必備的
  • 語法組合可分為:
    • if:一種選項,滿足條件,才執行某動作
    • if + else:兩種選項,滿足條件與其他狀況(不滿足條件),各執行某動作
    • if + elif:兩種選項,滿足各條件,各執行某動作
    • if + elif + (elif)... + (else):多種選項,滿足各條件,各執行某動作
  • 可以搭配邏輯運算子 & (and) 、 | (or)

Conditional judgment


Example

if (a > b):
    print ("a is greater than b")
elif (a < b):
    print ("a is less than b")
else:
    print ("a is equal to b")

Conditional judgment


In [1]:
a = 100
b = 95

if (a > b):
    print ("a is greater than b")
elif (a < b):
    print ("a is less than b")
else:
    print ("a is equal to b")
a is greater than b

Conditional judgment


Note

in 功能

  • 某個元素是否在串列中
In [2]:
my_string = "Hello Python!!"

if "H" in my_string:
    print("Found ","H")
else :
    print("Not Found")
Found  H

Exercise

Q. 利用 inif/else 判斷式,判斷 fruit 中有沒有 "apple"

fruit = ['banana', 'Wax apple','cherry', 'coconut', 'jujube', 'durian', 'grape', 'grapefruit', 'guava', 'lemon', 'pineapple', 'Watermelon', 'Kiwi', 'Orange', 'Longan', 'Blueberry', 'Mango']

Answers

In [3]:
fruit = ['banana', 'Wax apple','cherry', 'coconut', 'jujube', 'durian', 'grape', 'grapefruit', 'guava', 'lemon', 'pineapple', 'Watermelon', 'Kiwi', 'Orange', 'Longan', 'Blueberry', 'Mango']
In [4]:
if "apple" in fruit:
    print('I find apple!')
else:
    print('No apple.')
No apple.

Conditional judgment


Note

in 功能

in 後面放的是字串

"pineapple" or "Wax apple"
In [5]:
if "apple" in "pineapple":
    print('I find apple!')
else:
    print('No apple.')
I find apple!
In [6]:
if "apple" in "Wax apple":
    print('I find apple!')
else:
    print('No apple.')
I find apple!

Loop

Loop ( for )


  • 做重複的事

  • 語法

    for iterating_var in sequence:
        statements
    
    • 宣告一個 iterating_var (迭代變量)
    • 宣告一個 sequence (迴圈要跑的範圍)
    • 縮排並宣告 statements (每次迭代的時候要做什麼事)

NOTE 迭代子(iterating_var) 為 sequence 的內容

Loop ( for )


Example : 想要將 city 中字串的字母依序輸出

In [7]:
city = 'Taipei'

Method 1. 逐一 print 出來

In [8]:
print(city[0])
print(city[1])
print(city[2])
print(city[3])
print(city[4])
print(city[5])
T
a
i
p
e
i

Loop ( for )


Example : 想要將 city 中字串的字母依序輸出

city = 'Taipei'

Method 2. 利用 for

In [9]:
for i in city:
    print(i)
T
a
i
p
e
i

Exercise

Q. 現在有一個未來一週 Taipei 的溫度,希望分別印出每一天的溫度

Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]

Answers

逐一 print 出來

In [10]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
In [11]:
print(Temperature_Taipei[0])
print(Temperature_Taipei[1])
print(Temperature_Taipei[2])
print(Temperature_Taipei[3])
print(Temperature_Taipei[4])
print(Temperature_Taipei[5])
print(Temperature_Taipei[6])
22
24
19
19
30
21
25

Answers

利用 for

In [12]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
In [13]:
for i in Temperature_Taipei:
    print(i)
22
24
19
19
30
21
25

Loop


Note

range ( )

  • 一個整數的序列
  • 語法
range( start , stop , step )

NOTE

  • start: 起始值
  • stop: 結束值
  • step: 差值

Loop


Note

range ( )

  • 一個整數的序列
  • 語法
    range( start , stop , step )
    
In [14]:
print('range(10) 的型態 :' ,type(range(10)))
print('輸出 range(10) :' ,range(10))
print('利用 list range(10) 中的元素都輸出 :' ,list(range(10)))
range(10) 的型態 : <class 'range'>
輸出 range(10) : range(0, 10)
利用 list range(10) 中的元素都輸出 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Loop


Note

range ( )

  • 一個整數的序列
  • 語法
    range( start , stop , step )
    
In [15]:
print('range(0, 10) : ' ,list(range(0, 10)))
print('range(0, 10, 2) : ' ,list(range(0, 10, 2)))
print('range(1, 6, 2) : ' ,list(range(1, 6, 2)))
range(0, 10) :  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 10, 2) :  [0, 2, 4, 6, 8]
range(1, 6, 2) :  [1, 3, 5]

Loop ( for )


for & range( )

  • 語法

    for index in range(len(sequence)):
        print(sequence[index])
    

NOTE 迭代子 (index) 為 索引值

Loop ( for )


for & range( )

依序輸出一個 -5 到 5 間隔 1 的數列中的每個 element

In [16]:
for i in range(5, -6 , -1):
    print(i)
5
4
3
2
1
0
-1
-2
-3
-4
-5

Loop ( for )


for & range( )

依序輸出一個 -5 到 5 間隔 1 的數列中的每個 element

In [17]:
for i in range(-5, 6, 1):
    print(i)
-5
-4
-3
-2
-1
0
1
2
3
4
5

Loop ( for )


Review Example : 想要將 city 中字串的字母依序輸出

city = 'Taipei'

Method 2. 利用 for

In [18]:
city = 'Taipei'
for i in city:
    print(i)
T
a
i
p
e
i

Loop ( for )


Example : 想要將 city 中字串的字母依序輸出

city = 'Taipei'

Method 3. 利用 for & range( ) (索引值)

In [19]:
city = 'Taipei'
for i in range(0,len(city)):
    print(city[i])
T
a
i
p
e
i

Exercise

Q. 依序印出 city_list 中的元素

city = ['Taipei', ['Taichung',22],  {'Kaohsiung':25}]

NOTE 輸出不必是單一個值也可以是 list 或 dictionary

Answers

Method 1.

In [20]:
city_list = ['Taipei', ['Taichung',22], {'Kaohsiung':25}]
In [21]:
city = ['Taipei', ['Taichung',22],  {'Kaohsiung':25}]
for i in city:
    print (i)
Taipei
['Taichung', 22]
{'Kaohsiung': 25}

Method 2.

In [22]:
city_list = ['Taipei', ['Taichung',22], {'Kaohsiung':25}]
In [23]:
for i in range(len(city_list)):
    print (city_list[i])
Taipei
['Taichung', 22]
{'Kaohsiung': 25}

Loop ( for )


Note : 當 sequence 是一個 dictionary 會輸出 key 值

  • 語法

    for iterating_var in sequence:
        statements
    
In [24]:
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' }
In [25]:
print(weather_dict.keys())
dict_keys(['Taipei', 'Taichung', 'Tainan', 'Kaohsiung'])
In [26]:
for i in weather_dict:
    print(i)
Taipei
Taichung
Tainan
Kaohsiung

Loop ( for )


Note : 當 sequence 是一個 dictionary 欲輸出 value 值

  • 語法

    for iterating_var in sequence:
        statements
    
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' }
In [27]:
print(weather_dict.values())
dict_values(['rainy', 'cloudy', 'sunny', 'sunny'])
In [28]:
for v in weather_dict.values():
    print(v)
rainy
cloudy
sunny
sunny

Loop ( for )


Note : 當 sequence 是一個 dictionary 想同時輸出 key,value 值

  • 語法

    for iterating_var in sequence:
        statements
    
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' }
In [29]:
for (key, value) in weather_dict.items():
    print(key, ":", value)
Taipei : rainy
Taichung : cloudy
Tainan : sunny
Kaohsiung : sunny
In [30]:
for (key, value) in weather_dict.items():
    print("%s%s" % (key, value))
Taipei:rainy
Taichung:cloudy
Tainan:sunny
Kaohsiung:sunny

Loop ( for )


Note : zip

壓合兩個以上 list

  • 長度相同
In [31]:
Week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
In [32]:
list( zip( Week,Temperature_Taipei ) )
Out[32]:
[('SUN', 22),
 ('MON', 24),
 ('TUE', 19),
 ('WED', 19),
 ('THU', 30),
 ('FRI', 21),
 ('SAT', 25)]

Loop ( for )


Note : zip

壓合兩個以上 list

  • 長度不同
In [33]:
Week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
Weather_Taipei = ['Yes','Yes','No']
In [34]:
list( zip( Week,Temperature_Taipei,Weather_Taipei ) )
Out[34]:
[('SUN', 22, 'Yes'), ('MON', 24, 'Yes'), ('TUE', 19, 'No')]

Loop ( for )


for & zip( )

同時取得兩個以上 sequence 的值

In [35]:
for week ,temperature in zip( Week,Temperature_Taipei ):
    print(week ,temperature)
SUN 22
MON 24
TUE 19
WED 19
THU 30
FRI 21
SAT 25

Loop ( for )


Note : 同時取得 sequence 的索引值及其值

In [36]:
for index in range(len(Temperature_Taipei)): 
    print(index , ":", Temperature_Taipei[index])
0 : 22
1 : 24
2 : 19
3 : 19
4 : 30
5 : 21
6 : 25

Loop ( for )


Note : 利用 enumerate 同時取得 sequence 的索引值及其值

In [37]:
for index, temperature in enumerate(Temperature_Taipei): 
    print(index , ":", temperature)
0 : 22
1 : 24
2 : 19
3 : 19
4 : 30
5 : 21
6 : 25

Exercise

Q. 希望將 Temperature_Taipei 中的所有溫度都轉成華氏

Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]

公式: $Fahrenheit = Celsius × (9/5) + 32$

Answers

In [38]:
Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]
In [39]:
Fahrenheit_Temperature_Taipei = Temperature_Taipei * (9/5) + 32
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-82acf661b327> in <module>()
----> 1 Fahrenheit_Temperature_Taipei = Temperature_Taipei * (9/5) + 32

TypeError: can't multiply sequence by non-int of type 'float'

Wrong

NOTE list 不能做 element-wise 的運算

Answers

In [40]:
Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]
In [41]:
for i in Temperature_Taipei:
    print(i * (9/5) + 32)
71.6
75.2
66.2
66.2
86.0
69.80000000000001
77.0

Answers

NOTE 將轉成華氏的結果存在一個 list

In [42]:
Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]
In [43]:
Temperature_Taipei_Fahrenheit = []
for i in Temperature_Taipei:
    Temperature_Taipei_Fahrenheit.append( i * (9/5) + 32 )
print(Temperature_Taipei_Fahrenheit)
[71.6, 75.2, 66.2, 66.2, 86.0, 69.80000000000001, 77.0]

Exercise

Q. 利用 for 迴圈,計算 1 加到 100

公式: $ Total = \sum_{i=1}^{100} x_i $

NOTE

  • 提示1:可以利用 range來建立一個 1 到 100 的 list
  • 提示2:可以跟 sum() 對答案

Answers

sum( ) 對答案

In [44]:
sum( range(1,101) )
Out[44]:
5050

Method1.

In [45]:
total = 0
for i in range(1,101):
    total = total+i
print(total)
5050

Answers

sum( ) 對答案

In [46]:
sum( range(1,101) )
Out[46]:
5050

Method2.

In [47]:
total = 0
for i in range(1,101):
    total +=i
print(total)
5050

Exercise

Q. 利用 for 迴圈,計算 $5!$

公式: $ Factorial = \prod_{k=1}^{5} k $

Answers

Method1.

In [48]:
factorial = 1
for i in range(1,6):
    factorial = factorial * i
print(factorial) 
120

Method2.

In [49]:
factorial = 1
for i in range(1,6):
    factorial *= i
print(factorial) 
120

Loop ( while )


  • 做重複的事

  • 語法

    while expression:
        statements
    

Loop ( while )


  • 宣告一個 expression (若條件為True就會執行)
  • 縮排並宣告 statements (每次迭代的時候要做什麼事)

NOTE 所有的 for 迴圈,都可以改用 while 迴圈;反之則不一定

Loop ( while )


利用 while 迴圈,計算 1 加到 100

In [50]:
total = 0
i=0
while i < len(range(1,101)):
    total += range(1,101)[i]
    i += 1

print(i)    
print(total) 
100
5050

Loop ( Nested loops )


  • 迴圈中還有一個迴圈
  • 語法
    for iterating_var in sequence:
      for iterating_var in sequence:
          statements
      statements
    

    while expression:
      while expression:
          statements
      statements
    

Loop ( Nested loops )


Note : print 補充

  • 語法
print( [object] ,sep='' ,end='\n')
- sep: 表示每個想要輸出的 object 間的分隔符號,預設是 ' ' (空格)
- end: 表示每個 print 最後的結尾符號,預設是 \n (換行)

Loop ( Nested loops )


利用 Nested loops 寫一個九九乘表

In [51]:
for i in range(1,10):
    for j in range(1,10):
        k=i*j
        print (k , end=' ')
    print()  
1 2 3 4 5 6 7 8 9 
2 4 6 8 10 12 14 16 18 
3 6 9 12 15 18 21 24 27 
4 8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81 

Loop & Conditional judgment

Loop & Conditional judgment


利用 if.. else.. 判斷 list 中元素的狀況

Exercise

Q. 判斷 1 到 20 的序列中,哪些是偶數哪些是奇數,並分別輸出

NOTE 輸出樣式 : 1 是奇數

Answers

In [52]:
for i in range(0,21):
    if ( i % 2 == 0):
        print(i,'是偶數')
    else:
        print(i,'是奇數')
0 是偶數
1 是奇數
2 是偶數
3 是奇數
4 是偶數
5 是奇數
6 是偶數
7 是奇數
8 是偶數
9 是奇數
10 是偶數
11 是奇數
12 是偶數
13 是奇數
14 是偶數
15 是奇數
16 是偶數
17 是奇數
18 是偶數
19 是奇數
20 是偶數

Exercise

Q. 判斷未來 Taipei 一週天氣狀況,如果溫度小於 22 度就在家,否則就出門

Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]

Answers

In [53]:
Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]
In [54]:
for i in Temperature_Taipei :
    if i <= 22:
        print('在家')
    else :
        print('出門')
在家
出門
在家
在家
出門
在家
出門

Loop & Conditional judgment


利用 zip( )if.. else.. 比較兩個 list 中元素的大小

In [55]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
Temperature_Taichung = [23 , 22 , 19, 20, 29, 19, 27]
In [56]:
for Taipei, Taichung in zip(Temperature_Taipei, Temperature_Taichung) :
    if Taipei > Taichung :
        print('Taipei 好熱')
    elif Taipei < Taichung :
        print('Taichung 好熱')    
    else :
        print('Taipei Taichung 都好熱')
Taichung 好熱
Taipei 好熱
Taipei Taichung 都好熱
Taichung 好熱
Taipei 好熱
Taipei 好熱
Taichung 好熱

Loops II

Loops II


  • break : 離開
  • continue : 繼續

Loops II


Example

利用 forbreak 試寫出一個判斷,如果遇到非 sunny 的天氣就停止 print ,否則則 print 出天氣狀況

Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
In [57]:
Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
for day in Weather_Taipei :
    if day !='sunny':
        break   
    else :
        print(day)
sunny
sunny

Loops II


Example

利用 forcontinue 試寫出一個判斷, 只要是 sunny 的天氣就輸出

Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
In [58]:
Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
for day in Weather_Taipei :
    if day !='sunny':
        continue  
    else :
        print(day)
sunny
sunny
sunny

Exercise

Q. 現在有兩個 list 分別是 未來一週 Taipei 的天氣以及星期,請找出未來一週天氣為 sunny 的星期

Week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']

NOTE 提示:可以利用 zip

Answers

In [59]:
Week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
In [60]:
for i , j in zip(Week,Weather_Taipei) :
    if j != 'sunny':
        continue 
    else :
        print(i)  
SUN
MON
WED