W④-Python learning from ccClub
字典、錯誤處理、模組
Wiki topics:
EDU · Education & Learning
W④-Python learning from ccClub
[embed]Python 初學第十一講—錯誤與例外處理 如何處理並且避免發生錯誤medium.com
[embed]Python 初學第九講 — 字典 Dictionary,另一個存資料的好方法medium.com
[embed]Python 初學第十二講—檔案處理 利用程式進行讀/寫檔案的處理medium.com
[embed]Python 初學第十三講—模組 善用前人或過去的自己所寫的程式碼,讓工作事半功倍medium.com
字典、錯誤處理、模組
- 字典是一種資料型態,方便查找資料的工具
- 分為Key 和 Value ( key 必須是唯一且不可變的)
- 使用大刮號
{}d = {key_1: value, key_2: value_2} - 使用內建函數
dict()d = dict() - 取得value值 →
d[key]ord.get(key),若沒有對應的key值,則會出現error
新增條目或更新value
d[key]=valued.update({key:value})如果一次要更新很多筆資料,建議可以使用updatemethod
original_dict.update(new_dict)
#新增一個空白的字典d
d ={}
d['李白'] = '太白'
print(d['李白'])
d.update({'李白':'青蓮居士'})
print(d['李白']
刪除資料
del d[key]若字典沒有指定的key,將會產生errord.pop(key)使用pop會回傳"你要刪掉的那個值"
檢查指定的 key 是否存在於字典中
因為他只會找 key 值,所以傳 value 進去會回傳 False 喔
'key' in dict_name
比較運算子
利用“==”、 “!=”等兩個比較運算子,便可以判斷兩個字典是否包含相同的鍵-值對,== 的判定不會在乎順序,只要內容相同的話,都會判定為 True
dict_name_1 == dict_name_2
如果想要知道兩個字典是否為同一個物件呢?is 運算子
利用 is 運算子,則是可以判斷兩個字典是否為相同的物件。
在本例子,movie_1 和 movie_4 雖然包含相同的 key — value,但卻是不同的物件(不同東西)。 一般來說的使用方法如下:
dict1 is dict2
其他用法
- print(len(dict) #列印字典中的有多少對應關係
- print(dict.keys()) #列印字典中的key值
- print(dict.values())#列印字典中的value值
- print(dict.items()) #列印字典的key&values
對字典跑迴圈
d = {'name':'Rebel Wilson','year':1980}
#針對字典中的key值跑迴圈
for key in d:
print(key, d[key])
#print出字典中的key值和value
for key in d.keys():
print(key, d[key])
d = {'name':'Rebel Wilson','year':1980}
#針對字典中的value值跑迴圈
for value in d.values():
print(value)
#print出字典中的value
for key,value in d.items():
print(key, value)
#print出字典中的key和value
使用for-loop來產生字典
dict_squares = {}
for i in range(6):
dict_squares[i] = i**2
print(dict_squares)
dict_squares = {i: i**2 for i in range(6)}
print(dict_squares)
對於一個已經建立的字典 my_squares,我們也可以使用for-loop將其內容逐一列印出來:
my_squares = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
for i in my_squares:
print(“Key is”, i, “Value is”, my_squares[i])
錯誤和例外處理
避免程式因為例外而暫停
Try — except
Try:
欲嘗試執行的程式碼
Except:
當程式執行的失敗時,欲執行的程式碼
例外處理結構外程式碼
- 在try-except的結構下,程式會首先執行try底下的程式碼

num1 = input()
num2 = input()
try:
print(int(num1) + int(num2)) #假設例外處理1
except:
print('請輸入阿拉伯數字')
print('繼續執行')
指定except去接住特定的例外,並做對應處理
num1 = input()
num2 = input()
try:
print(int(num1) / int(num2)) #假設例外處理1
except ValueError:
print('請輸入阿拉伯數字')
except ZeroDivisionError:
print('除數不可為零')
print('繼續執行')
常見的例外類型
- SyntaxError 語法錯誤
- NameError 變數名稱錯誤
- TypeError 類型錯誤
- ValueError 值錯誤
- IndentationError 縮排錯誤
- IndexError 索引值錯誤
- ZeroDivisionError 除數為零的錯誤
搭配 else 以及 finally
try:
#嘗試執行的程式碼
except 例外名稱:
#當遇到特定的例外時要執行的程式碼
except:
#當未指定的例外發生時要執行的程式碼
else:
#若 try 當中的程式碼並未產生例外時要執行的區塊
finally:
#無論如何都要執行的程式碼
當 try 當中的程式可以正確地執行,將會執行 else 區塊當中的程式碼;而無論 try 區塊中的程式碼執行以後有沒有產生例外,都要執行 finally 區塊中的程式碼。
檔案處理-開啟
有兩個參數,檔名(填入檔案路徑)和mode
f = open(檔名, mode='模式')
r唯讀模式,可以讀取但不能做更動,如果檔案不存在,則會產生FileNotFoundError。w: 覆寫模式,可以寫入檔案,會覆蓋掉原始檔,如果檔案不存在,則會新增一個檔案。a: 續寫模式,會從原本檔案的最後繼續進行寫入。
檔案處理-關閉
f.close()
- 因為可以開啟的檔案數量是有上限的,所以在結束檔案的操作之後,記得將檔案關閉
檔案處理-讀取
f.read([size])
size參數沒有設定時,會讀取檔案的所有內容- 如果有設定
size,會讀取指定的字節數量
f = open('file.txt', 'r')
first_line = f.readline()
second_line = f.readline()
print(second_line, first_line, sep = '\n')
f.close()
- 讀取檔案中整行的資料,但一次只會讀取一行
f.readlines()
- 將檔案內的資料逐行讀取,將其回傳成一個list
- 常常與for迴圈搭配使用
f = open('file1.txt','r')
for line in f.readlines():
print(line)
f.close()
檔案處理-寫入檔案(string)
f.write(內容)
f.writelines(數列)
print(資料,file=f)
f = open ('file2.txt','w')
f.write('ccClub is the best\nLet\'s learn Python')
f.close()
f = open ('file3.txt','w')
seq = ['ccClub is the best\n','Let\'s learn Python']
f.writelines(seq)
f.close()
f = open('file4.txt', 'w')
movies = ['Up', 'Inside Out',
'Titanic', 'Forrest Gump',
'Mad Max: Fury Road']
print(movies, file=f)
f.close()
模組 import.模組
math:math.fabs(x)numpypandasrandom:random.randint(x,y)(生成>=x且<=y的整數),random.random()(生成>=0且<1的浮點數),random.uniform(x,y)(生成>=x且≤y的浮點數),random.choice(seq)(隨機取出數列中的數字)datetimestatistics:statistics.mean()requestsbeautifulsoup
import math
print(math.cos(0))
print(math.pi)
print(mathe.sqrt(2))
import statistics as st
s = [1,2,3,4,5]
print(st.mean(s))
print(st.median(s))
print(st.stdev(s))
print(st.mode(s))
import random
print(random.randint(1,10))
print(random.random())
print(random.uniform(1.1,5.4)
print(random.choice('hello!')) 메타데이터
- post_id
- ce7e7a83ea3e
- slug
- w④-python-learning-from-ccclub-ce7e7a83ea3e
- url
- https://medium.com/%E8%89%BE%E8%9C%9C%E8%8E%89%E8%AE%80%E8%AE%80%E5%AF%AB%E5%AF%AB/w%E2%91%A3-python-learning-from-ccclub-ce7e7a83ea3e
- canonical_url
- https://medium.com/%E8%89%BE%E8%9C%9C%E8%8E%89%E8%AE%80%E8%AE%80%E5%AF%AB%E5%AF%AB/w%E2%91%A3-python-learning-from-ccclub-ce7e7a83ea3e
- author_url
- https://medium.com/@yuhan02011
- status
- ok
- fetched_at
- 2026-07-24 23:44:46