D-LAB Python X 使用者體驗設計

Pyladies Taiwan

Speaker : Mars

2016/10/20

Roadmap

  • Python 簡介
  • jupyter使用簡介
  • 變數
  • 輸入與輸出
  • 字串與串列
  • 判斷式

Python 簡介

  • 簡潔易懂
  • 要求程式碼寫作風格
  • 可以做很多事情

應用

  • [網路爬蟲]:urllib、requests、lxml、beautiful_soup、scrapy、selenium
  • [資料庫串接]:sqlite3(sqlite)、MySQLdb(MySQL)、pymssql(MSSQL)、Psycopg(PostgreSQL)
  • [自然語言]:NLTK、jieba
  • [統計應用]:pandas、numpy、scipy、matplotlib
  • [機器學習]:scikit-learn、TensorFlow
  • [影像處理]:PIL、opencv
  • [網站架設]:Django、Flask
  • [網路分析]:scapy
  • [GUI設計]:tkinter、PyQt
  • [軟硬整合]:raspberry pi 樹莓派、Arduino
  • [遊戲開發]:pygame
  • [App開發]:kivy
  • [各種服務的API串接]:Bot

程式設計

幫我們自動化處理事情,減少重複的動作

程式設計 Roadmap

  • [基礎學習]:變數型態、判斷式、迴圈、函式、類別、模組、檔案IO、例外處理
  • [進階技巧]:Effective Python
  • [各種應用]

使用jupyter撰寫&執行 第一隻Python 程式

  • 新增一個Notebook (New > Notebooks | Python [default])
  • 輸入程式碼 print ("Hello PyLadies"),按下介面上的 或是用快捷鍵Ctrl+EnterShift+Enter編譯執行

!注意

  • 如果有用到上方cell的程式碼內容,需要先編譯執行上方cell的程式碼
  • 如果針對現在的cell多次編譯執行,並不會影響到上方cell已編譯執行後的結果

變數

變數

  • 變數是一個容器,是資料的儲存空間
  • 在程式中「=」是「賦值」的意思:將右邊的資料儲存到左邊的變數
    my_score = 96
    pi = 3.14159
    url = "http://blog.marsw.tw"
    
  • my_score、pi、url 都是自行命名的變數
  • 可以命名的字元:_、0~9、a~Z

!注意

  • 不能以數字開頭
  • 不能與保留字相同(ex: import, for, in, str....)
  • 大小寫有別
  • 好的命名方式會讓程式碼容易閱讀
    • xyz = "http://blog.marsw.tw" vs.
      url = "http://blog.marsw.tw"

變數型別

  • type(變數):印出此變數的型別
In [19]:
my_score = 96
pi = 3.14159
url = "http://blog.marsw.tw"

print (type(my_score))
print (type(pi))
print (type(url))
<class 'int'>
<class 'float'>
<class 'str'>

Python 是一個動態性的語言

  • 同樣的變數可以隨時更動他的變數型別
In [20]:
my_score = 96
print (type(my_score))

my_score = 96.0
print (type(my_score))

my_score = "96"
print (type(my_score))
<class 'int'>
<class 'float'>
<class 'str'>

數值

  • 整數 integer:int
  • 小數 float:float
  • 運算元:+ - * / % **
In [22]:
a = 96
b = 80
c = a+b
print (a+b,c)
print (a-b)
176 176
16
In [25]:
print (10*3)  # 乘法
print (10/3)  # 除法
print (10%3)  # 取餘數
print (10**3) # 次方
30
3.3333333333333335
1
1000

運算元的簡潔寫法

  • a+= ba = a+b
  • a-= ba = a-b
  • a*= ba = a*b
In [98]:
count = 0
count+= 1 
print (count)
count*= 3
print (count)
count-= 2
print (count)
1
3
1

字串(string)

  • 可以直接給定詞句
  • 也可以給空白句
  • 可以相+ (但不能相-)
  • 可以彈性填入詞句:使用「%s
In [103]:
my_string = "Hi"
my_string2 = ""
my_string2 = my_string2 + "Py" + "Ladies"
my_string3 = "Py%s Taiwan"%("Ladies")

print (type(my_string))
print (my_string)
print (my_string2)
print (my_string3)
<class 'str'>
Hi
PyLadies
PyLadies Taiwan

!注意

  • 用「成對的」雙引號"或是單引號',將字串包住
  • 若遇到長篇文章有換行的存在,可用「三個」雙引號或單引號
In [70]:
article = """
Bubble tea represents the "QQ" food texture that Taiwanese love. 
The phrase refers to something that is especially chewy, like the tapioca balls that form the 'bubbles' in bubble tea. 
It's said this unusual drink was invented out of boredom. 
"""
print (article)
Bubble tea represents the "QQ" food texture that Taiwanese love. 
The phrase refers to something that is especially chewy, like the tapioca balls that form the 'bubbles' in bubble tea. 
It's said this unusual drink was invented out of boredom. 

格式化字串 %s 應用情境

In [83]:
# 產生各股票網址(股票代號是在網址中,不是在尾端)
url = "http://www.wantgoo.com/stock/%s?searchType=stocks"%(2330)
print (url)
url = "http://www.wantgoo.com/stock/%s?searchType=stocks"%(2371)
print (url)
http://www.wantgoo.com/stock/2330?searchType=stocks
http://www.wantgoo.com/stock/2371?searchType=stocks
In [65]:
# 造句
my_sentence = ("%s就是要%s呀,不然要幹嘛?")%("颱風","泛舟")
print (my_sentence)
my_sentence = ("%s就是要%s呀,不然要幹嘛?")%("夏天","吃冰")
print (my_sentence)
颱風就是要泛舟呀,不然要幹嘛?
夏天就是要吃冰呀,不然要幹嘛?

!注意

  • 字串與數值不可一同運算
In [46]:
my_string = "123"
my_int_number = 456
print (my_string+my_int_number)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-ec3cf0d0f296> in <module>()
      1 my_string = "123"
      2 my_int_number = 456
----> 3 print (my_string+my_int_number)
      4 

TypeError: Can't convert 'int' object to str implicitly

型別轉換

  • int(變數):將變數轉成整數(integer)型別,變數不可包含小數點!
  • float(變數):將變數轉成小數(float)型別
  • str(變數):將變數轉成字串(string)型別
In [53]:
input1 = 123
input2 = "456"
input3 = "5566.123"
print (str(input1)+input2)
print (input1+int(input2))
print (float(input3)+input1)
123456
579
5689.123

輸入與輸出

  • input(提示字):從鍵盤輸入變數
    • 輸入的變數為字串型別
  • print(變數):輸出變數到螢幕上
    • 可以用,印出多個變數(印出後,會以空白分隔變數)
In [60]:
a = input("a=")
b = input("b=")
print ("a+b=",a+b)
a=123
b=456
a+b= 123456

[練習] 變數&輸入與輸出

會有兩次輸入,分別輸入兩個數字,印出

  • 兩數字相加結果
  • 兩數字相除結果
  • 兩數字次方項結果

字串與串列

串列(list)

  • 可以直接給定有值的串列
  • 也可以給空串列
  • 串列的增加是使用 append()
  • 串列的組成可以不必都是同樣類型的元素
In [244]:
my_list = ["a",2016,5566,"PyLadies"]
my_list2=[]
my_list2.append(2016)
my_list2.append("abc")
print (my_list)
print (my_list2)
['a', 2016, 5566, 'PyLadies']
[2016, 'abc']

串列每個元素的位置

In [254]:
my_list = ["a",2016,5566,"PyLadies",2016,2016.0]
print ("The 4th  element of my_list = ",my_list[3])
print ("The last element of my_list = ",my_list[-1]) 
print ("The second-last element of my_list = ",my_list[-2]) 
The 4th  element of my_list =  PyLadies
The last element of my_list =  2016.0
The second-last element of my_list =  2016

「字串」 其實是 "每個元素都是一個字母" 的 「串列」

In [239]:
my_string = "PyLadies Taiwan"
print ("The 1st  element of my_string = ",my_string[0])
print ("The 8th  element of my_string = ",my_string[7])
print ("The last element of my_string = ",my_string[-1]) 
The 1st  element of my_string =  P
The 8th  element of my_string =  s
The last element of my_string =  n

字串&串列,可通用的功能

  • len:計算長度
  • count:計算某個元素出現過幾次
In [241]:
my_string = "PyLadies Taiwan"
print ("Length of my_string = ",len(my_string))
print ("The time 'a' appears in my_string = ",my_string.count('a'))
Length of my_string =  15
The time 'a' appears in my_string =  3
In [242]:
my_list = ["a",2016,5566,"PyLadies",2016,2016.0]
print ("Length of my_list = ",len(my_list))
print ("The time '2016' appears in my_string = ",my_list.count(2016))
Length of my_list =  6
The time '2016' appears in my_string =  3

字串split、replace功能

replace

  • 處理後字串 = 原字串.replace(舊字串,新字串):將「原字串」中「舊字串」都取代為「新字串」,產生「處理後字串」
In [16]:
my_string = "PyLadies Taiwan"
my_string = my_string.replace("a","A")
print (my_string)
my_string = my_string.replace("T","L")
print (my_string)
my_string = my_string.replace("LA","")
print (my_string)
PyLAdies TAiwAn
PyLAdies LAiwAn
Pydies iwAn

replace 應用情境

In [1]:
# 景點改名
article="中正紀念堂,位於臺北市中正區,全區250,000平方公尺,主樓高76公尺;園區廣場的南北側,另建有國家表演藝術中心國家兩廳院管理的國家戲劇院和國家音樂廳,落成以來成為臺北市在國際上最著名地標之一。中正紀念堂全區面積達250,000平方公尺,除了高76公尺的主建築外,還有國家戲劇院、國家音樂廳(合稱「兩廳院」),以及主建築前的瞻仰大道、中央藝文廣場(亦稱自由廣場)、園區環外迴廊、中式庭園(光華池及雲漢池)等。中正紀念堂設計時,即隱含豐富的象徵語彙。外表以藍、白2色為主,象徵中華民國國徽中的「青天白日」,紀念堂平面為方形格局,象徵蔣中正的「中正」,坐東面西,遙望大陸。仿效北京天壇和廣州中山紀念堂的琉璃瓦八角攢尖頂代表八德,而隱藏其中的人形象徵天人合一。紀念堂正面共有花崗石84階、大廳階梯5階,合計89階,表示蔣中正享壽89歲。臺階中間為中華民國國徽圖案的丹陛,在中國傳統建築上,只用於宮殿或廟堂。"
article=article.replace("中正紀念堂","臺灣民主紀念園區")
print (article)
臺灣民主紀念園區,位於臺北市中正區,全區250,000平方公尺,主樓高76公尺;園區廣場的南北側,另建有國家表演藝術中心國家兩廳院管理的國家戲劇院和國家音樂廳,落成以來成為臺北市在國際上最著名地標之一。臺灣民主紀念園區全區面積達250,000平方公尺,除了高76公尺的主建築外,還有國家戲劇院、國家音樂廳(合稱「兩廳院」),以及主建築前的瞻仰大道、中央藝文廣場(亦稱自由廣場)、園區環外迴廊、中式庭園(光華池及雲漢池)等。臺灣民主紀念園區設計時,即隱含豐富的象徵語彙。外表以藍、白2色為主,象徵中華民國國徽中的「青天白日」,紀念堂平面為方形格局,象徵蔣中正的「中正」,坐東面西,遙望大陸。仿效北京天壇和廣州中山紀念堂的琉璃瓦八角攢尖頂代表八德,而隱藏其中的人形象徵天人合一。紀念堂正面共有花崗石84階、大廳階梯5階,合計89階,表示蔣中正享壽89歲。臺階中間為中華民國國徽圖案的丹陛,在中國傳統建築上,只用於宮殿或廟堂。
In [104]:
# 資料正規化
brand = "APPLE"
brand = brand.replace("A","A").replace("P","P").replace("L","L").replace("E","E")
print (brand)
APPLE

split

  • 字串串列 = 原字串.split(子字串):將「原字串」以「子字串」切割為「字串串列」
In [108]:
my_string = "PyLadies Taiwan"
print (my_string.split(" "))
print (my_string.split(" ")[0])
print (my_string.split(" ")[-1])
['PyLadies', 'Taiwan']
PyLadies
Taiwan

split 應用情境

In [28]:
# 取得一篇文章的單字
article = "Bubble tea represents the 'QQ' food texture that Taiwanese love. The phrase refers to something that is especially chewy, like the tapioca balls that form the 'bubbles' in bubble tea. It's said this unusual drink was invented out of boredom. Chun Shui Tang and Hanlin Tea Room both claim to have invented bubble tea by combining sweetened tapioca pudding (a popular Taiwanese dessert) with tea. Regardless of which shop did it first, today the city is filled with bubble tea joints. Variations on the theme include taro-flavored tea, jasmine tea and coffee, served cold or hot."
print (article.split(" "))
print ("The 1st word of this article is",article.split(" ")[0])
['Bubble', 'tea', 'represents', 'the', "'QQ'", 'food', 'texture', 'that', 'Taiwanese', 'love.', 'The', 'phrase', 'refers', 'to', 'something', 'that', 'is', 'especially', 'chewy,', 'like', 'the', 'tapioca', 'balls', 'that', 'form', 'the', "'bubbles'", 'in', 'bubble', 'tea.', "It's", 'said', 'this', 'unusual', 'drink', 'was', 'invented', 'out', 'of', 'boredom.', 'Chun', 'Shui', 'Tang', 'and', 'Hanlin', 'Tea', 'Room', 'both', 'claim', 'to', 'have', 'invented', 'bubble', 'tea', 'by', 'combining', 'sweetened', 'tapioca', 'pudding', '(a', 'popular', 'Taiwanese', 'dessert)', 'with', 'tea.', 'Regardless', 'of', 'which', 'shop', 'did', 'it', 'first,', 'today', 'the', 'city', 'is', 'filled', 'with', 'bubble', 'tea', 'joints.', 'Variations', 'on', 'the', 'theme', 'include', 'taro-flavored', 'tea,', 'jasmine', 'tea', 'and', 'coffee,', 'served', 'cold', 'or', 'hot.']
The 1st word of this article is Bubble

replace 與 split 應用情境

In [85]:
# 日期正規化 (年-月-日 時:分:秒)
ebc_datetime = "2016-10-17 17:00"
back_datetime = "2016-10-11, 19:55"
ptt_datatime = "Tue Oct 18 23:22:05 2016"

format_ebc_datetime = ebc_datetime+":00"
format_back_datetime = back_datetime.replace(",","")+":00"

# ptt
ptt_split_list = ptt_datatime.split(" ")
ptt_year = ptt_split_list[-1]
ptt_month = ptt_split_list[1].replace("Oct","10")
ptt_date = ptt_split_list[2]
ptt_time = ptt_split_list[3]
format_ptt_datetime = ptt_year+"-"+ptt_month+"-"+ptt_date+" "+ptt_time


print (format_ebc_datetime)
print (format_back_datetime)
print (format_ptt_datetime)
2016-10-17 17:00:00
2016-10-11 19:55:00
2016-10-18 23:22:05

字串功能使用情境1

  • 找出文章中某單字出現次數,以「in」 為例
In [74]:
article = """
Bubble tea represents the "QQ" food texture that Taiwanese love. 
The phrase refers to something that is especially chewy, like the tapioca balls that form the 'bubbles' in bubble tea. 
It's said this unusual drink was invented out of boredom. 
"""
print (article.count("in"))
4

實際上「in」這個「單字」在文章中只出現一次,
但因為用count,把只要有出現「in」:someth"in"g、"in"、dr"in"k、"in"vented
不管他是一個單字或是包含在其他單字出現剛好in的子字串都算進去。

所以我們應該先將文章分割成一個個單字,再來計算!

In [75]:
word_of_article = article.split(" ")
print (word_of_article.count("in"))
1

字串功能使用情境2

  • 找出文章中某單字出現次數,以「tea」 為例
In [76]:
article = """
Bubble tea represents the "QQ" food texture that Taiwanese love. 
The phrase refers to something that is especially chewy, like the tapioca balls that form the 'bubbles' in bubble tea. 
It's said this unusual drink was invented out of boredom. 
"""
word_of_article = article.split(" ")
print (word_of_article.count("tea"))
1

可是文章中我們有看到兩次的tea,怎麼只算一次?
原因是因為split之後,是分成「tea」、「tea.」
這兩個是不同的字串,以count("tea")來說,就只會算到剛好等於「tea」的字

所以可以先將常用標點符號取代之後再來計算!

In [99]:
clean_article = article.replace(".","").replace(",","").replace(":","")
clean_article = clean_article.replace("?","").replace("\"","").replace("\'","")
word_of_article = clean_article.split(" ")
print (word_of_article.count("tea"))
2

串列 數值計算、join 功能

數值計算

  • ! 針對全數字串列才有用
  • max(串列):串列中最大值
  • min(串列):串列中最小值
  • sum(串列):串列總和
In [105]:
my_list = [3, 4.0, 2.1, 1]
print (max(my_list))
print (min(my_list))
print (sum(my_list))
4.0
1
10.1

應用情境

In [106]:
# 統計全班成績狀況
score_of_each_student = [85,70,54,87,98,66,40]
avg_score = sum(score_of_each_student) / len(score_of_each_student)
print ("全班分數落差為",max(score_of_each_student)-min(score_of_each_student))
print ("全班平均為",avg_score)
全班分數落差為 58
全班平均為 71.42857142857143

join

  • 與split分割相反,是將字串串列以某個字串組合起來
  • ! 針對全字串串列才有用
In [82]:
my_list = ["Hello","PyLadies","Taiwan"]
print (" ".join(my_list))
Hello PyLadies Taiwan

join 應用情境

In [97]:
# 列出選項
free_date_list=[]
free_date_list.append(input())
free_date_list.append(input())
free_date_list.append(input())
print ("有空的時間",",".join(free_date_list))
10/19
10/21
10/22
有空的時間 10/19,10/21,10/22

延伸學習-切割序列

2016/10/01 PyLadies Python讀書會 - 01 by 毛毛
Effective Python - 第 1 章 Pythonic 思維 - 05 知道如何切割序列

判斷式:if/elif/else

  • if是判斷式必備的
    • if:一種選項,滿足條件,才執行某動作
    • if + else:兩種選項,滿足條件與其他狀況(不滿足條件),各執行某動作
    • if + elif:兩種選項,滿足各條件,各執行某動作
    • if + elif + (elif)... + (else):多種選項,滿足各條件,各執行某動作
  • 邏輯運算元:and、or、not
In [93]:
a = 11
b = 8
if (a > b) and (a%2==0):
    print ("a>b")
    print ("a is even")
elif a>b:
    print ("a>b")
    print ("a is odd")
else:
    print ("a<=b")
print ("這是判斷式外的區塊")
a>b
a is odd
這是判斷式外的區塊

「a%2」代表的意思是 a 除以 2 的「餘數」
而「==」代表的意思是 <左邊的條件>「是否等於」<右邊的條件>

Python是靠「縮排」(四個空白),來斷定程式碼屬於那一個區塊。

in 功能

  • 找出某子字串是否在字串中
  • 找出某元素是否在串列中
In [136]:
my_string = "PyLadies Taiwan"

if "PyLadies" in my_string:
    print ("\"PyLadies\" found")
if "Python" in my_string:
    print ("\"Python\" found")
if "Taiwan" in my_string:
    print ("\"Taiwan\" found")
"PyLadies" found
"Taiwan" found

用「\"」的原因是因為,我們宣告字串已經是用「"」,像是"PyLadies Taiwan"
但我想要印出「"」,而又不想要被當作宣告用的指令,因此會打「\」來做「跳脫」

!注意

跟前面的練習一樣,如果是要找單字,記得先分割成單字的字串才使用

In [80]:
my_string = "PyLadies Taiwan"
if "Py" in my_string:
    print ("\"Py\" found in my_string")

my_string_list = my_string.split(" ")
if "Py" in my_string_list:
    print ("\"Py\" found in my_string_list")
"Py" found in my_string

總練習

今天所教的語法應用情境

In [89]:
# 日期正規化 (年-月-日 時:分:秒)
yahoo_datetime = "2016年10月18日 下午10:33"
temp_yahoo_date = yahoo_datetime.split(" ")[0].replace("年","-").replace("月","-")
temp_yahoo_date = temp_yahoo_date.replace("日","")
temp_yahoo_time = yahoo_datetime.split(" ")[-1]
temp_yahoo_hour = temp_yahoo_time.split(":")[0]
temp_yahoo_mins = temp_yahoo_time.split(":")[-1]

if "下午" in temp_yahoo_hour:
    temp_yahoo_hour_int = int(temp_yahoo_hour.replace("下午",""))+12
    temp_yahoo_hour = str(temp_yahoo_hour_int)
else:
    temp_yahoo_hour_int = int(temp_yahoo_hour.replace("上午",""))
    temp_yahoo_hour = str(temp_yahoo_hour_int)

format_yahoo_datetime = temp_yahoo_date+" "+temp_yahoo_hour+":"+temp_yahoo_mins+":00"
print (format_yahoo_datetime)
    
2016-10-18 22:33:00

[練習]

簡易型計算機(加減乘除、次方、餘數),
輸入一行文字,印出計算結果

  • 只會有兩個數字,與一個運算元

ex:

  • 11+2 -> 13
  • 2**3 -> 8
  • 10%3 -> 1

進階變數處理

  • 取小數點後n位:round(變數,n)
  • 印出格式化長度為n的數值(在前補零):字串變數.zfill(n)
In [37]:
pi = 3.14159
pi_2 = round(pi,2)
print (pi_2)
print (str(pi_2).zfill(5))
3.14
03.14

[think]

  • 我想要輸入10個不相等的變數
  • 我想要輸入一串數組ex:(1,2,3,4,5),然後印出相加的總和
  • 我想要算出字串"「1」、「5」、「7」、「3」、「2」、「6」"出現數字的總和
    data = "「1」、「5」、「7」、「3」、「2」、「6」"
    data = data.replace("「","") 
    data = data.replace("」","")
    print (data)
    print (data.split("、"))
    

sum只能用在純數字的串列,
split後的是字串的串列......

CheckIO

以上都是今天教得語法可以解的題目

沒有頭緒嗎?下一頁有提示用哪些語法去解題

CheckIO