本教材有錄製教學影片,可從底下網址連結。 > https://w3.uch.edu.tw/vipent/python # 第1章 Python開發環境 Python官方網站 + IDLE Anaconda + Spyder Anaconda + Jupyter Notebook Google Colab ## 1-1 IDLE Python官方網站:https://www.python.org/ ![image](https://hackmd.io/_uploads/B139kR8N1e.png) ### 執行安裝程式 python-3.13.1.exe Python 3.13.1 - Dec. 3, 2024 安裝後 IDLE (Python 3.13 64-bit) 交談式開發環境 Python 3.13(64-bit) 命令視窗 Python 3.13 Manuals(64-bit) 使用手冊 Python 3.13 Module Docs(64-bit) 模組文件 ### 使用IDLE (1)開新檔案並執行 (2)開啟舊檔 備註1:Python的副檔名是 .py 備註2:IDLE Shell 3.13是交談式開發環境,可執行簡單命令,並非撰寫、儲存程式碼的地方。要點選File才是開新檔案或開啟舊檔。 ![image](https://hackmd.io/_uploads/ryU-AmY4yx.png) 備註3:執行結果會顯示在IDLE Shell 3.13。 ![image](https://hackmd.io/_uploads/S1Ob_EKEJl.png) ### 練習1-1 First.py ``` python= # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ print("Welcome to Python") print("This is my first program") print("Python is fun") ``` ### 註解 1. 單行註解:\# 後面的文字不會被執行,是作為單行註解。 2. 多行註解:前面、後面各放"""(三個雙引號)或'''(三個單引號) ### 數學計算 在python中,可直接使用四則運算(+ - * /) print( 2 + 3 * 4 ) 另外,試看看 print(" 2 + 3 * 4 ")會顯示什麼呢? ### 作業1-1 請寫一個python,執行後產出 Hello, I love Python. Python is useful. ## 1-2 Spyder Anaconda官網:https://www.anaconda.com/ 安裝完Anaconda,可使用Spyder或Jupyter Notebook。 ### 使用Spyder (1)開新檔案並執行 (2)開啟舊檔 ![image](https://hackmd.io/_uploads/B16w_EF4yg.png) ## 1-3 Jupyter Notebook ### 使用Jupyter Notebook 執行Jupyter Notebook,將會開啟瀏覽器來做後續執行。 (1)開新檔案並執行 (2)開啟舊檔 備註1:Jupyter Notebook所產出的檔案副檔名為 .ipynb。 ![image](https://hackmd.io/_uploads/HkeNEEtEyg.png) 備註2:每個單元格(cell)有3種選項。 1. Code:編寫程式碼 2. Markdown:文本編輯 3. Raw NBConvert:純文字 ![image](https://hackmd.io/_uploads/r1dlP4YE1x.png) ## 1-4 Google Colab Google Colab https://colab.research.google.com/ Colab (全名為「Colaboratory」) 可讓你在瀏覽器中編寫及執行 python 程式碼,並具有以下優點: (1)不必進行任何設定 (2)免付費使用 GPU (3)輕鬆共用 Colab 是由 Google 在雲端運行並託管的 Jupyter Notebooks 環境,不需要設定就可以使用。透過瀏覽器編寫並執行 Python 程式碼,並將檔案直接存在 Google 雲端硬碟。 | 名稱 | Jupyter Notebook | Colab | | --- | ---- | --- | | 程式碼 | Code | 程式碼 | | 文字 | Markdown<br>Raw NBConvert | 文字 | | 檔案位置 | 本機 | 雲端 | ### 使用Google Colab (1)開新檔案並執行 (2)開啟舊檔 ![image](https://hackmd.io/_uploads/r1PnI4tE1x.png) # 第2章 輸出與輸入 ## 2-1 輸出print ### print print是輸出函數。 用雙引號 "abc" 包起來的稱為字串。 (ps.用單引號包起來也是一樣的) print("abc") 和 print('abc') 都是顯示abc。 錯誤的寫法 print(abc),會出現<font color="#f00">NameError</font>。 abc會被視為變數,但是目前變數並沒有被定義。 ### 變數 將字串或數值儲存在變數。 字串 a="uch" print(a) 執行結果會得到 uch 數值 a=100 print(a) 執行結果會得到 100 a=15 b=10 print(a+b) 執行結果會得到 25,此為數字相加。 a="15" b="10" print(a+b) 執行結果會得到 1510,此為字串相加。 注意:字串和數字是不能相加的。 以下是錯誤寫法,會出現<font color="#f00">TypeError</font>。 a=15 b="10" print(a+b) 可修改成print(str(a)+b) 或是 print(a+int(b)) ### 其他賦值方式 多重賦值 a,b=15,10 print(a+b) 增量賦值 a=10 a += 1 相當於 a = a+1 print(a) ### 轉換型態 a=15 為數值型態 str(a) 為字串型態 b="10" 為字串型態 int(b)為整數型態、float(b)為浮點數型態 使用type可以知道目前型態為何 type(a) type(str(a)) ### 練習2-1 字串格式化 ``` python= # 輸出結果 張無忌18歲 # 方法1 (字串) print("張無忌18歲") # 以下先設定好兩個變數 name="張無忌" age=18 # 方法2 (使用3個項目) print(name, age, "歲") # 方法3 (使用+將字串結合) print(name+str(age)+"歲") # 方法4 (%字串格式化 ) print("%s%d歲" %(name,age)) # 方法5 (format字串格式化) print("{}{}歲" .format(name,age)) # 方法6 (f-String) print(f"{name}{age}歲") ``` ### 作業2-1 將日期2025-01-01設為變數date,組員姓名設為變數name,健行行銷系設為變數dep 日期:2025-01-01 組員:張無忌、令狐沖 我們讀健行行銷系 我們喜歡Python ### 關鍵字參數 sep=分隔字元:印多個項目,項目之間以分隔字元隔開。 end=結束字元:列印完畢時,加入結尾處。 ``` python= print("健","行","科","技","大","學",sep="&",end=".") ``` ### 長字串 ``` python= print("""這是個長字串 前後用三個雙引號(或三個單引號)包住 可以任意換行 """) # 先設定變數 msg = """這是個長字串 前後用三個雙引號(或三個單引號)包住 可以任意換行 """ print(msg) ``` ### 變數命名原則 1. 變數名稱只能由大小寫英文、數字、_、中文所組成。(建議避免使用中文) 2. 變數名稱的開頭不能是數字。 3. 英文字母大小寫視為不同變數名稱。 4. 變數名稱不能與Python保留字相同。 錯誤的變數命名,會出現<font color="#f00">SyntaxError</font>,例如 1. 7_11,開頭是數字。 2. H&M,不能有特殊符號 &。 3. for,為保留字。 ### 資料型態 | 名稱 | type | 範例 | | --- | ---- | --- | | 字串 | str | "uch" | | 整數 | int | 10 | | 浮點數 | float | 3.14 | | 布林值 | bool | True, False | ## 2-2 輸入input ### input input是輸入函數。 ### 練習2-2 ``` python= name = input("請輸入姓名:") age = input("請輸入年齡:") print(f"{name}{age}歲" ) ``` ### 練習2-3 ``` python= chinese = int(input("請輸入中文成績:")) math = int(input("請輸入數學成績:")) total = chinese + math print(f"總成績為{total}") ``` ### 作業2-2 BMI 設計BMI計算程式,使用者輸入姓名、身高、體重。 BMI = 體重(kg) / 身高(m)^2 請輸入您的姓名:王小明 請輸入您的身高(cm):183 請輸入您的體重(kg) :78 王小明您好 您的身高183公分,體重78公斤,BMI值為23.29 ## 2-3 運算子 ### 算術運算子 | 運算子 | 作用 | 範例 | 範例結果 | | --- | ---- | --- | --- | | + | 加法 | 5+2 | 7| | - | 減法 | 5-2 | 3| | * | 乘法 | 5\*2 | 10| | / | 除法 | 5/2 | 2.5| | // | 除法取商數 | 5//2 | 2| | % | 除法取餘數 | 5%2 | 1| | ** | 次法 | 5\*\*2 | 25| ### 比較運算子 | 運算子 | 作用 | 範例 | 範例結果 | | --- | ---- | --- | --- | | == | 是否相等 | 5==2 | False| | != | 是否不相等 | 5!=2 | True| | > | 是否大於 | 5>2 | True| | >= | 是否大於或等於 | 5>=2 | True| | < | 是否小於 | 5<2 | False| | <= | 是否小於或等於 | 5<=2 | False| ### 邏輯運算子 | 運算子 | 作用 | 範例 | 範例結果 | | --- | ---- | --- | --- | | not | 否定 | not(5==2) | True| | and | 且 | (5>3) and (7==4+2) | False| | or | 或 | (5>3) or (7==4+2) | True| 備註 1. not(True)=False, not(False)=True。 2. 當A,B都是True,則(A and B)為True;其他情形為False。 2. 當A,B都是False,則(A or B)為False;其他情形為True。 # 第3章 判斷式 ## 3-1 單向判斷式 if 條件式: &ensp;&ensp;&ensp;&ensp;程式區塊 注意:縮排統一空4格。 ### 練習3-1 ``` python= pw = input("請輸入密碼(提示:一種動物,3個字母):") if pw == "pig": print("歡迎光臨") ``` ## 3-2 雙向判斷式 if 條件式: &ensp;&ensp;&ensp;&ensp;程式區塊1 else: &ensp;&ensp;&ensp;&ensp;程式區塊2 ### 練習3-2 ``` python= pw = input("請輸入密碼(提示:一種動物,3個字母):") if pw == "pig": print("歡迎光臨") else: print("密碼錯誤") ``` ### 作業3-1 讓使用者依序輸入兩個整數,顯示出最大值。 請輸入第1個整數:50 請輸入第2個整數:90 最大值為:90 ## 3-3 多向判斷式 if 條件式: &ensp;&ensp;&ensp;&ensp;程式區塊1 elif 條件式: &ensp;&ensp;&ensp;&ensp;程式區塊2 else: &ensp;&ensp;&ensp;&ensp;程式區塊3 ### 練習3-3 ``` python= age = int(input("請輸入您的年齡:")) if 0 < age < 13: print("兒童票") elif 13 <= age < 19: print("青年票") elif 19 <= age < 60: print("全票") else: print("敬老票") ``` ### 作業3-2 讓使用者輸入分數(0\~100的整數),顯示出等級。 90以上為優等,80\~89為甲等,70\~79為乙等,其他為丙等。 請輸入分數:85 等級:甲等 ## 3-4 巢狀判斷式 判斷式裡面又有判斷式,要注意縮排。 ### 練習3-4 讓使用者依序輸入三個整數,顯示出最大值。 請輸入第1個整數:50 請輸入第2個整數:90 請輸入第3個整數:70 最大值為:90 ``` python= a = int(input("請輸入第1個整數:")) b = int(input("請輸入第2個整數:")) c = int(input("請輸入第3個整數:")) if a > b: if a > c: print(f"最大值為:{a}") else: print(f"最大值為:{c}") else: if b > c: print(f"最大值為:{b}") else: print(f"最大值為:{c}") ``` # 第4章 迴圈 ## 4-1 for迴圈 ### range函式 range(整數值) range(5) 內容為0,1,2,3,4 range(起始值,終止值) range(1,5) 內容為1,2,3,4 range(起始值,終止值,間隔值) range(1,5,2) 內容為1,3 ### for 迴圈 for 變數 in 可迭帶的物件: &ensp;&ensp;&ensp;&ensp;程式區塊 可迭帶的物件包含:字串、串列、字典等。 ``` python= for n in range(5): print(n, end=",") ``` ``` python= for n in range(1,10,2): print(n, end=",") ``` ``` python= for n in "morning": print(n, end=",") ``` ### 練習4-1 輸入一個正整數,會計算出從1到該正整數的總和。 請輸入正整數:5 1到5的整數和為 15 ``` python= n = int(input("請輸入正整數:")) sum=0 for i in range(1,n+1): sum += i print(f"1到{n}的整數和為{sum}") ``` ### 練習4-2 九九乘法表 ``` python= for i in range(1,10): for j in range(1,10): print(f"{i}*{j}={i*j:2d}", end=" ") print() ``` ### break break:強制結束迴圈。 ``` python= for word in "management": if word == "a": break print(word) ``` ### continue continue:強制結束本次迴圈,進入下一次迴圈。 ``` python= for word in "management": if word == "a": continue print(word) ``` ### 作業4-1 輸入一個正奇數,會列出1到該正奇數的所有奇數,並計算這些奇數的總和。 請輸入正奇數:9 1到9的奇數有 1 3 5 7 9 總和為 25 ## 4-2 while迴圈 ### while迴圈 while 條件式: &ensp;&ensp;&ensp;&ensp;程式區塊 條件式如果為真True,則執行程式區塊,並進入下一次迴圈; 條件式如果為假False,則結束迴圈。 備註:要注意不要寫出無窮迴圈,若出現疑似無窮迴圈,程式執行不完,可按Ctrl+C來強制結束程式。 ### 練習4-3 3n+1猜想 ``` python= n = int(input("請輸入一個大於1的正整數:")) while n > 1: if n%2 == 0: n = int(n/2) else: n = 3*n+1 print(n) ``` ### 練習4-4 ``` python= while True: pw = input("請輸入密碼(提示:一種動物,3個字母):") if pw == "pig": print("歡迎光臨") break else: print("密碼錯誤") ``` ### 作業4-2 將練習題4-4,修改成至多只能輸入密碼3次。 # 第5章 容器 常見的容器有下列4種。 串列list [1,2,3,4] 有索引值,可修改內容。 元組tuple (1,2,3,4) 有索引值,不可修改內容。 集合set {1,2,3,4} 沒有重複的元素,可修改內容。 字典dict {"a":1,"b":2,"c":3,"d":4} 沒有重複的鍵(key),可修改內容。 ## 5-1 串列list ### 串列宣告 ``` python= A=[1,2,3] B=["行銷", "資管", "企管"] C=["行銷", 20, "企管"] D=[] # 空串列 E=[["行銷",2],["企管",5],["資管", 10]] ``` 第一個位置的索引值為0,之後依序加1。 ``` python= print(E[0]) print(E[1][1]) ``` ### 串列搜尋 B=["行銷", "資管", "企管"] 串列. index(元素值) B.index("資管") 使用index會回傳第一次找到該元素的索引。 若是串列沒有該元素,則會出現<font color="#f00">ValueError</font>。 ### 串列新增元素 A=[1,2,3] 串列. append(元素值) A.append(4) 新增元素4在最後面。 串列. insert(索引值,元素值) A.insert(1,5) 新增元素5在索引值1的位置。 ### 串列刪除元素 B=["行銷", "資管", "企管"] 串列. remove(元素值) B. remove("企管") 串列. pop(索引值) B.pop(0) 刪除索引值0的元素。 B.pop() 刪除最後一個元素。 del 串列[索引值] del B[1] ### 練習5-1 成績輸入-for ``` python= N = int(input("請輸入學生人數:")) names = [] scores = [] for i in range(N): name = input("請輸入學生姓名:") names.append(name) score = int(input("請輸入數學分數:")) scores.append(score) for i in range(len(names)): print(f"{names[i]}的分數為{scores[i]}") mean = sum(scores) / len(scores) print(f"班上平均分數為{mean:.2f}") ``` ### 練習5-2 成績輸入-while ``` python= names = [] scores = [] print("請輸入學生姓名、成績,當輸入 -1 時結束") while True: name = input("請輸入學生姓名:") if name == "-1": break names.append(name) score = int(input("請輸入數學分數:")) scores.append(score) for i in range(len(names)): print(f"{names[i]}的分數為{scores[i]}") mean = sum(scores) / len(scores) print(f"班上平均分數為{mean:.2f}") ``` ### 作業5-1 銷售明細 請輸入當天的銷售明細,包含產品名稱、單價、數量。 當產品名稱輸入-1時,結束輸入,並印出銷售明細,並顯示當天售出的總金額。 ## 5-2 元組tuple ### 串列與元組 A = ["a","b","c"] 為串列,可修改內容。 B = (4,5) 為元組,不可修改內容。 串列與元組的轉換 C=tuple(A) 為元組 D=list(B) 為串列 元組有索引值,可使用index C.index("c") ## 5-3 集合set ### 集合 集合特性:沒有重複的元素,沒有索引值,可修改內容。 A=set() 空集合;B={} 為空字典。 串列與集合的轉換 A=[1,2,3,2,1] B=set(A) C=list(B) ### 集合修改 新增 B.add(4) B.add("uch") 刪除 B.remove(4) ## 5-4 字典dict ### 字典 A={"apple":20, "banana":15, "lemon":10} {鍵1:值1,鍵2:值2,鍵3:值3} 每個項目當中,用 : 隔開,前面為鍵(key),後面為值(value)。 字典沒有重複的鍵,沒有索引值,可修改內容。 二維串列轉字典 A=[["apple",20], ["banana", 15], ["lemon", 10]] B=dict(A) ### 字典修改 fruit={} 空字典 新增: fruit["apple"]=20 fruit["banana"]=15 修改: fruit["banana"]=10 刪除: del fruit["banana"] ### 字典取值 fruit["apple"] fruit["banana"] 如沒有此鍵,則發生<font color="#f00">KeyError</font>。 fruit.get("banana") 如沒有此鍵,則回傳None。 ### 練習5-3 水果價錢 ``` python= dict1={} while True: key = input("請輸入水果名稱,當輸入 -1 時結束:") if key == "-1": break value = input("請輸入水果單價(元/斤):") dict1[key]=value print(dict1) print("底下將進行查詢") while True: key = input("請輸入水果名稱,當輸入 -1 時結束:") if key == "-1": break value = dict1.get(key) print(f"{key}一斤{value}元") ``` ### 字典進階操作 字典的一些方法,keys()、values()、items()。 ### 練習5-4 ``` python= dict1 = {"apple":20, "banana":15, "lemon":10} print(len(dict1)) #字典元素個數 K = dict1.keys() #取得字典所有的鍵 print(K) V = dict1.values() #取得字典所有的值 print(V) T = dict1.items() #取得字典所有的(鍵,值)組合 print(T) ``` ### 練習5-5 ``` python= dict1 = {"apple":20, "banana":15, "lemon":10} print("使用keys()方法") for k in dict1.keys(): v = dict1.get(k) print(f"{k}一斤{v}元") print() print("使用items()方法") for k, v in dict1.items(): print(f"{k}一斤{v}元") ``` ### 作業5-2 英漢字典 請製作英漢字典,輸入英文當key,輸入中文當value。當英文輸入-1時,結束輸入,並印出字典內容。 # 第6章 函式與模組 ## 6-1 函式 ### 函式 內建函式:如print()、input()。 自訂函式:使用def 引用函式(已安裝模組):使用import 引用函式(未安裝模組):需先使用pip安裝,才可以import。 ### 自訂函式 先定義,再使用。 ``` python= def test(): print("您好") test() ``` def 函式名稱(參數1,參數2) &ensp;&ensp;&ensp;&ensp;程式區塊 &ensp;&ensp;&ensp;&ensp;return 回傳值1, 回傳值2 備註 1. 參數可有可無,可1個,也可以多個。 2. 回傳值可有可無,可1個,也可以多個。如沒有回傳值就不寫return。 ### 練習6-1-1 ``` python= print("您好") print("歡迎湯姆光臨健行樂園") print("祝您有愉快的一天") print("您好") print("歡迎大衛光臨健行樂園") print("祝您有愉快的一天") print("您好") print("歡迎瑪莉光臨健行樂園") print("祝您有愉快的一天") print("您好") print("歡迎凱蒂光臨健行樂園") print("祝您有愉快的一天") ``` ### 練習6-1-2 ``` python= names=["湯姆","大衛","瑪莉","凱蒂"] for name in names: print("您好") print(f"歡迎{name}光臨健行樂園") print("祝您有愉快的一天") ``` ### 練習6-1-3 ``` python= def hello(name): print("您好") print(f"歡迎{name}光臨健行樂園") print("祝您有愉快的一天") names=["湯姆","大衛","瑪莉","凱蒂"] for name in names: hello(name) ``` ### 練習6-2-1 ``` python= h = int(input("請輸入您的身高(cm):")) w = int(input("請輸入您的體重(kg):")) bmi = w / (h /100)**2 print(f"您的BMI值為{bmi:.2f}" ) ``` ### 練習6-2-2 ``` python= def BMI(h,w): bmi = w / (h /100)**2 return bmi h = int(input("請輸入您的身高(cm):")) w = int(input("請輸入您的體重(kg):")) print(f"您的BMI值為{BMI(h,w):.2f}" ) ``` ### 自建模組 將以下內容存成B.py ``` python= def hello(name): print("您好") print(f"歡迎{name}光臨健行樂園") print("祝您有愉快的一天") ``` 開啟新檔,要和B.py放在同一個工作目錄 ``` python= import B B.hello("Fred") B.hello("Mary") ``` ### 全域與區域 ``` python= def test(): a = 100 b = 200 global e # 宣告為全域變數 e = 500 print(a) # 100,a為區域變數。 print(c) # "lemon",區域找不到c,往上層尋找。 print(d) # NameError,區域與全域都找不到d。 a = "apple" c = "lemon" test() print(a) # "apple",a為全域變數。 print(b) # NameError,全域找不到b。 print(e) # 500,e為全域變數。 ``` 當區域找不到該變數,則會往上層尋找。 當全域找不到該變數,不會往下層尋找。 ## 6-2 模組 ### random模組 方法1 import 模組 import random random.random() random.randint(1,10) 方法2 import 模組 as 別名 import random as r r.random() r.randint(1,10) 方法3 from 模組 import 函式 from random import randint randint(1,10) 方法4 from 模組 import * from random import * random() randint(1,10) ### 練習6-3 丟骰子 ``` python= import random as r def dice(): n1 = r.randint(1,6) n2 = r.randint(1,6) n3 = r.randint(1,6) total = n1+n2+n3 print(f"您丟出{n1},{n2},{n3}") return total print("總和是",dice()) ``` ### 練習6-4 猜數字 ``` python= import random as r num = r.randint(1,10) k = 0 while True: ans = int(input("請從1~10猜一個數字:")) k += 1 if ans == num: print("恭喜您猜對了") print(f"您共猜了{k}次") break print("猜錯了") ``` ### 作業6-1 猜拳 利用random模組,寫一個與電腦猜拳的遊戲。採先獲3勝者為贏家,結束時列出雙方勝場數,並判定最後輸贏。 ### 安裝模組-python官方 打開 cmd cd C:\Users\user\AppData\Local\Programs\Python\Python313\Scripts pip install 模組名稱 pip install requests ### 安裝模組-Anaconda 打開 cmd cd C:\Users\user\anaconda3\Scripts pip install 模組名稱 pip install requests ### 政府資料開放平臺 政府資料開放平臺 https://data.gov.tw/ 職災職能復健專責醫院名單 https://data.gov.tw/dataset/44745 ### 練習6-5 ``` python= import requests import csv # 將網址存放到變數 url = "https://apiservice.mol.gov.tw/OdService/download/A17000000J-030081-SrV" # 到網路上去抓資料 response = requests.get(url) # 將資料切割成獨立的每一筆資料 data = response.text.splitlines() # 將每一筆資料內的每一個欄位資料拆開 rows = list(csv.reader(data)) # 使用for-in迴圈將每一筆資料取出 for row in rows: print(row) ``` ### 亂碼處理 ``` python= # 若印出內容為亂碼,可檢查編碼方式,並指定編碼 print(response.encoding) #查看網頁返回的字符集類型 print(response.apparent_encoding) #自動判斷字符集類型 response.encoding = response.apparent_encoding #通過res.apparent_encoding屬性指定編碼 ``` # 第7章 檔案與例外處理 ## 7-1 檔案操作 ### os模組 ``` python= import os print(os.getcwd()) # 列出目前工作目錄 os.mkdir("test") # 建立資料夾test os.rmdir("test") # 刪除資料夾test os.rename("t1.txt", "t2.txt") # 將t1.txt更名為t2.txt os.remove("t2.txt") # 刪除檔案t2.txt ``` ### txt檔案 建立uch.txt檔案,內容如下,並將檔案放置工作目錄。 ``` 健行科技大學 Chien Hsin University of Science and Technology 網址:https://www.uch.edu.tw/ 地址:桃園市中壢區健行路229號 電話:03-4581196 ``` ### 練習7-1-1 txt檔案-用for迴圈讀取 ``` python= fn = "uch.txt" f = open( fn ,"r", encoding="utf-8") for data in f: print(data,end="") f.close() ``` ### 練習7-1-2 txt檔案-用read讀取 ``` python= fn = "uch.txt" f = open( fn ,"r", encoding="utf-8") data = f.read() f.close() print(data) ``` ### 練習7-1-3 txt檔案-使用with open ``` python= fn = "uch.txt" with open( fn ,"r", encoding="utf-8") as f: data = f.read() print(data) ``` ### open 與 with open的差異 使用open開啟檔案,就必須使用close關掉檔案。 使用with open,底下敘述必須縮排,當語法結束會自動關閉該檔案。 ### 練習7-1-4 txt檔案-使用 readlines ``` python= fn = "uch.txt" with open( fn ,"r", encoding="utf-8") as f: data = f.readlines() print(data) ``` 備註:使用 readlines,會讀取全部內容,回傳為一個串列,每一行會成為串列的一個元素。 ### 練習7-2 txt檔案-使用write寫入檔案 ``` python= fn = "uch-w.txt" content = "I love uch" with open( fn ,"w", encoding="utf-8") as f: f.write(content) ``` 備註:若原檔案不存在,則會建立檔案。若原檔案存在,則會先清空內容。 ### 練習7-3 CSV檔案-讀取與寫入 ``` python= import requests import csv # 將網址存放到變數 url = "https://apiservice.mol.gov.tw/OdService/download/A17000000J-030081-SrV" response = requests.get(url) # 到網路上去抓資料 # 將資料切割成獨立的每一筆資料 data = response.text.splitlines() # 將每一筆資料內的每一個欄位資料拆開 rows = list(csv.reader(data)) # 使用for-in迴圈刪除不需要的欄位 for row in rows: del row[2:5] del row[0] fn = "職災職能復健專責醫院名單-csv.csv" with open ( fn ,"w", newline="", encoding="utf-8") as f: fWriter = csv.writer(f) for row in rows: fWriter.writerow(row) ``` ### 練習7-4 CSV檔案-讀取與寫入EXCEL ``` python= import requests import csv import openpyxl # 將網址存放到變數 url = "https://apiservice.mol.gov.tw/OdService/download/A17000000J-030081-SrV" response = requests.get(url) # 到網路上去抓資料 # 將資料切割成獨立的每一筆資料 data = response.text.splitlines() # 將每一筆資料內的每一個欄位資料拆開 rows = list(csv.reader(data)) # 建立Excel資料表 wb = openpyxl.Workbook() wb.active.title = "職災職能復健專責醫院名單" ws = wb.active row_index = 1 for row in rows: ws.cell(column=1, row=row_index, value=row[1]) ws.cell(column=2, row=row_index, value=row[5]) row_index = row_index + 1 wb.save("職災職能復健專責醫院名單-csv.xlsx") ``` ### 練習7-5 EXCEL讀取與寫入 ``` python= import openpyxl wb = openpyxl.load_workbook("py_excel.xlsx") ws = wb.active ws.cell(column=3, row=1, value="乘積") for i in range(2,ws.max_row+1): n1 = ws.cell(column=1, row=i).value n2 = ws.cell(column=2, row=i).value n3 = n1*n2 ws.cell(column=3, row=i, value=n3) wb.save("py_excel_new.xlsx") ``` ### 作業7-1 使用者輸入同學的姓名、成績,最後將資料儲存成Excel檔案。 ## 7-2 例外處理 ### 例外處理語法 try: &ensp;&ensp;&ensp;&ensp;執行測試的程式區塊 except: &ensp;&ensp;&ensp;&ensp;處理例外情形的程式區塊 else: &ensp;&ensp;&ensp;&ensp;沒有發生例外情形時執行的程式區塊 finally: &ensp;&ensp;&ensp;&ensp;一定會執行的程式區塊 ### 練習7-6 ``` python= try: a=int(input("請輸入第1個整數:")) b=int(input("請輸入第2個整數:")) c=a+b print(f"整數和為{c}") except: print("輸入錯誤") ``` 通常針對特定錯誤給予特定的處理方式,以下是常見的錯誤。 | 方法 | 說明 | | ---- | ---- | | 語法錯誤 | SyntaxError、IndentationError、TabError | | 名稱錯誤 | NameError | | 型態錯誤 | TypeError、AttributeError | | 值錯誤 | ValueError | | 列表、字典相關 | IndexError、KeyError、LookupError | | 計算相關 | ZeroDivisionError | | 模組相關 | ImportError、ModuleNotFoundError | | 檔案相關 | FileExistsError、FileNotFoundError | | 文字相關 | UnicodeEncodeError、UnicodeDecodeError | ### 練習7-7 ``` python= try: a=int(input("請輸入第1個整數:")) b=int(input("請輸入第2個整數:")) c=a/b print(f"{a}除以{b}為{c:.2f}") except ValueError: print("請輸入數字") except ZeroDivisionError: print("分母不能為0") ``` ---------------- # 第8章 視窗程式設計 ## 8-1 tkinter 使用tkinter模組,可以寫出視窗版本的程式。 參考網址 https://steam.oxxostudio.tw/category/python/tkinter/start.html | 方法 | 說明 | 內部功能 | | ---- | ---- | ---- | |TK | 建立視窗 | title(標題)、geometry(視窗大小) | |Lable | 標籤 | config(更改內容) | |Entry | 輸入框 | get(取得內容)、delete(刪除內容) | |Button | 按鈕 | ### 佈局 1. pack() 基本佈局,由上而下 2. grid() 格狀佈局,類似Excel表格 3. place() 位置佈局,由座標決定 ### 練習8-1 BMI視窗版 ``` python= import tkinter as tk def BMI(): name = entry1.get() height = float(entry2.get()) weight = float(entry3.get()) bmi = weight / (height/100)**2 msg=f"{name}的身高 {height} 公分,體重 {weight} 公斤,BMI值為 {bmi:.2f}" label4.config(text=msg) window = tk.Tk() window.title("計算BMI") window.geometry("400x300") label1 = tk.Label(window,text="姓名") label1.grid(row=0,column=0,padx=10,pady=0) label2 = tk.Label(window,text="身高(cm)") label2.grid(row=1,column=0,padx=10,pady=0) label3 = tk.Label(window,text="體重(kg)") label3.grid(row=2,column=0,padx=10,pady=0) label4 = tk.Label(window,text="") label4.grid(row=4,column=0,columnspan=2,padx=0,pady=20) entry1 = tk.Entry(window) entry1.grid(row=0,column=1,padx=20,pady=20) entry2 = tk.Entry(window) entry2.grid(row=1,column=1,padx=20,pady=20) entry3 = tk.Entry(window) entry3.grid(row=2,column=1,padx=20,pady=20) button = tk.Button(window,text="計算",command=BMI) button.grid(row=3,column=1) window.mainloop() ``` ### 作業8-1 製作一個溫度轉換程式視窗版,攝氏與華式可以互相轉換。 (轉換公式:華氏 = 攝氏\*1.8 + 32)