Python × 資料分析

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


利用 判斷式 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

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.

Note

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
    

Loop ( for )


  • 宣告一個 iterating_var (迭代變量)

  • 宣告一個 sequence (迴圈要跑的範圍)

  • 縮排並宣告 statements (每次迭代的時候要做什麼事)

Loop ( for )


Example

city = 'Taipei'

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

Loop ( for )


In [7]:
city = 'Taipei'
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 [8]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
In [9]:
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 [10]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
In [11]:
for i in Temperature_Taipei:
    print(i)
22
24
19
19
30
21
25

Note

range ( )

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

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

Note

range ( )

In [12]:
print(range(10))
range(0, 10)
In [13]:
print(type(range(10)))
<class 'range'>
In [14]:
print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note

range ( )

In [15]:
print(list(range(0, 10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [16]:
print(list(range(0, 10, 2)))
[0, 2, 4, 6, 8]
In [17]:
print(list(range(1, 6, 2)))
[1, 3, 5]

Loop ( for )


for & range( )

利用 for statements 和 range( )
依序輸出一個 -5 到 5 間隔 1 的數列中的每個 element

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

Loop ( for )


for & range( )

利用 for statements 和 range( )
依序輸出一個 -5 到 5 間隔 1 的數列中的每個 element

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

Loop ( for )


Method 1.

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

Loop ( for )


Method 2.

In [21]:
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}]

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

Answers

Method 1.

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

Method 2.

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

Loop ( for )


  • 語法

    for iterating_var in sequence:
        statements
    

    當 sequence 是一個 dictionary 會輸出 key 值

In [26]:
weather_dict = { 'Taipei':'rainy', 'Taichung':'cloudy' , 'Tainan':'sunny' , 'Kaohsiung':'sunny' }
In [27]:
print(weather_dict.keys())
dict_keys(['Taipei', 'Taichung', 'Tainan', 'Kaohsiung'])
In [28]:
#輸出 key 值
for i in weather_dict:
    print(i)
Taipei
Taichung
Tainan
Kaohsiung

Loop ( for )


  • 語法

    for iterating_var in sequence:
        statements
    

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

In [29]:
#輸出Key,Value
for (key, value) in weather_dict.items():
    print(key, ":", value)
Taipei : rainy
Taichung : cloudy
Tainan : sunny
Kaohsiung : sunny

Note

zip

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

Note

zip

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

Loop ( for )


for & zip( )

利用 for statements 和 zip( )
同時取得兩個以上 sequence 的值

In [34]:
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

Note

enumerate

  • 同時取得 sequence 的索引值及其值
In [35]:
#不使用 enumerate
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

Note

enumerate

  • 同時取得 sequence 的索引值及其值
In [36]:
#使用 enumerate
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. 利用 for statements 解決 list 不能逐項運算(element-wise) 的問題。希望將 Temperature_Taipei 中的所有溫度都轉成華氏

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

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

Answers

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

Note

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

In [39]:
Temperature_Taipei = [22, 24, 19, 19, 30, 21, 25]
In [40]:
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 $

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

Answers

sum( ) 對答案

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

Method1.

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

Answers

sum( ) 對答案

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

Method2.

In [44]:
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 [45]:
factorial = 1
for i in range(1,6):
    factorial = factorial * i
print(factorial) 
120

Method2.

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

Loop ( while )


  • 做重複的事

  • 語法

    while expression:
        statements
    

Loop ( while )


  • 宣告一個 expression (若條件為True就會執行)

  • 縮排並宣告 statements (每次迭代的時候要做什麼事)

Loop ( while )


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

In [47]:
total = 0
i=0
while i < len(range(1,101)):
    total += range(1,101)[i]
    i += 1
print(total) 
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 )


利用 Nested loops 寫一個九九乘表

In [48]:
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. 判斷未來 Taipei 一週天氣狀況,如果溫度小於 22 度就在家,否則就出門

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

Answers

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

Loop & Conditional judgment


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

In [51]:
Temperature_Taipei = [22 , 24 , 19, 19, 30, 21, 25]
Temperature_Taichung = [23 , 22 , 19, 20, 29, 19, 27]
In [52]:
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 [53]:
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 試寫出一個判斷, print 出所有 sunny 的天氣

Weather_Taipei = ['sunny','sunny','cloudy','sunny','rainy','cloudy','rainy']
In [54]:
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']

Answers

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

提示:可以利用 zip