Day 15 ~ Day 31
Introduction
阿彌陀佛,計畫總是趕不上變化
網址 :https://www.udemy.com/course/100-days-of-code/
程式碼:https://github.com/deathpc/python_100day/
Day 15
之前都是用Jupyter & VScode,切換語言(R, python, autoit, PHP, javascript, HTML, kotlin...雖然樣樣不精(~ ̄▽ ̄)~) ,突然要測功能蠻方便的,不過還是載了Pycharm 下來試試
- TO DO List Tracking
在程式碼中插入 [#TODO: 待辦事項內容] ,可藉由編譯器的功能追蹤待辦事項 - Alt+4
切換至 Run 視窗 - Mutable Default Arguments
因為 python 的函式也是物件,預設參數也算是函式物件的屬性之一。因此當函式的預設參數為 mutable 物件時,在函式的定義階段,預設參數這個屬性就被定義完成了。之後無論函式被呼叫幾次是不會再重新定義的,會發生以下結果:def test(ele, ele_list=[]):
ele_list.append(ele)
return ele_lists
test(3) #output: [3]
test(4) #output: [3,4]
- Windows Emoji
Windows button + . 可以叫出 Emoji 鍵盤……太神啦~!🐸
Day 16
Turtle module是一種簡易的繪圖程式,在Python中為內建模組,直接載入模組就能使用函式功能來控制Turtle動作和繪圖應用。
PyPI(The Python Package Index)
PyPI 是一個軟體套件儲存庫(software package repository),上面存有各組織及社群發佈的Python套件
PyPI 是一個軟體套件儲存庫(software package repository),上面存有各組織及社群發佈的Python套件
If A and B
If Statement with and 的情況下,A 判斷式執行完若為真,不會執行B判斷式
If Statement with and 的情況下,A 判斷式執行完若為真,不會執行B判斷式
Pycharm
- Pycharm 中可使用 virtualenv 建立乾淨的虛擬環境,建立虛擬環境後可透過settings 安裝想要的套件,以此避免跟其他專案的環境,保持專案的環境簡潔(如下圖):

- 對package 名稱點擊右鍵→Go To→Implementation(s) 可查看套件的程式碼
Day 17
這一天比較完整的初步講解Class在Python中的作用
在Python中類別的命名盡量採PascalCase,其他則使用snake_case
Day 18 - 21
利用 turtle 模組帶入Class的使用方式與繼承概念。
- Slicing
a[start:stop] # 取出 a 中位置 start 至 stop-1 的元素
a[start:] # 取出 a 中位置 start 至結尾的元素
a[:stop] # 取出 a 中位置開頭至stop-1 的元素
a[:] # 複製整個 list
a[start:stop:step] # 每次間隔 step 取出 a 中位置 start 至 stop-1 的元素
a[-1] # 取出最後一個元素
a[-2:] # 取出最後二個元素
a[:-2] # 取出所有元素,除了最後二個
a[::-1] # 反轉List
Day 22-23
透過實現經典的乒乓球與烏龜過街遊戲加深對物件導向熟悉度,其中 turtle.getcanvas() 這個 method 可以搭配 bind 來實現較複雜的按鍵偵測,對tkinter較熟悉的人應該不陌生。
Day 24
- 能使用 if-else 解決的事情,就不要濫用 try-catch
- Too broad exeption clause - PEP 8: do not use bare 'exept'
- 在使用 try-catch 語法時,單純的except將抓取所有異常,包括 KeyboardInterrupt 與其它不符預期的異常。
- 若沒有期望會出現的異常類型,至少宣告為 except Exception。
- 宣告異常類型可幫助開發者發現、紀錄、縮小問題範圍並解決問題。
try:
pass # 嘗試執行的部份
except ValueError as ex: # 抓取到指定例外時執行
print(ex)
except (RuntimeError, IndexError) as ex: # 抓取到列舉的複數例外時執行
print(ex)
else:
pass # 沒有抓取到例外時執行
finally:
pass # 一定會執行的部分
Day 25
在Python中對於外部資料(txt, csv)的讀取常見可分為三種做法:
- 內建的 open + read系列函式
- 透過 csv 模組
- 透過 pandas 模組
with open("weather_data.csv") as f:
data = f.readlines()
# ##########################
import csv
with open("weather_data.csv") as f:
data = csv.reader(f)
# ##########################
import pandas as pd
data = pd.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")
對欄位做分組取數量
data_frame.groupby('column_name').size()
對資料框架的列作迭代
data_frame.iterrows()結尾實作了一個考美國州名的小遊戲
Day 26
List Comprehension 是 Python 獨有的快速產生列表的簡潔語法,但若需對多個變數同時作處理,考慮到可讀性,建議還是採用 For Loop去編寫較為洽當
new_list = [new_item for item in list if condition] new_list = [new_item if condition else new_item2 for item in list]
在 Pycharm 中可以開啟 Python 的Console,甚至透過 GUI 直接改變物件的值,在測試語法的時候相當便利

Day 27-31
參數的預設值及無數量限制的位置參數與關鍵字參數傳入
def function(arg1, arg2=3, arg3=7): #default value
pass
def function(*args): # unlimited positional arguments
print(args) # It will return args as a tuple
def function(**kwargs): # unlimited keyword arguments
print(kwargs) # It will return kwargs as a dict
Tkinter
JSON (JavaScript Object Notation)
- Widgets
- Tk
整個介面最上層的元件window = Tk()
window.title("Widget Examples")
window.minsize(width=500, height=500) window.mainloop() - Label
文字標籤label = Label(text="This is old text")
label.config(text="This is new text") - Button
按鈕def action():
print("Do something")
button = Button(text="Click Me", command=action) - Entry
文字輸入框entry = Entry(width=30)
entry.insert(END, string="Some text to begin with.")
print(entry.get()) - Text
文字方塊text = Text(height=5, width=30)
#Puts cursor in textbox.
text.focus()
#Adds some text to begin with.
text.insert(END, "Example of multi-line text entry.")
#Get's current value in textbox at line 1, character 0
print(text.get("1.0", END)) - Spinbox
調整器def spinbox_used():
#gets the current value in spinbox.
print(spinbox.get())
spinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used) - Scale
拉桿def scale_used(value):
print(value)
scale = Scale(from_=0, to=100, command=scale_used) - Checkbutton
勾選按鈕def checkbutton_used():
#Prints 1 if On button checked, otherwise 0.
print(checked_state.get())
#variable to hold on to checked state, 0 is off, 1 is on.
checked_state = IntVar()
checkbutton = Checkbutton(text="Is On?", variable=checked_state, command=checkbutton_used)
checked_state.get() - Radiobutton
單選按鈕def radio_used():
print(radio_state.get())
#Variable to hold on to which radio button value is checked.
radio_state = IntVar()
radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used)
radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used) - Listbox
列表def listbox_used(event):
# Gets current selection from listbox
print(listbox.get(listbox.curselection()))
listbox = Listbox(height=4)
fruits = ["Apple", "Pear", "Orange", "Banana"]
for item in fruits:
listbox.insert(fruits.index(item), item)
listbox.bind("<<ListboxSelect>>", listbox_used)
- Canvas
畫布canvas1 = Canvas(width=200, height=200, bg=YELLOW, highlightthickness=0)
img_tomato = PhotoImage(file="tomato.png")
canvas1.create_image(100, 112, image=img_tomato) text_timer = canvas1.create_text(100, 132, text="00:00", fill="white", font=(FONT_NAME, 35, "bold"))canvas1.itemconfig(text_timer, text="lalala")
- Layout
pack跟Grid不可同時使用 - Pack
打包於相對位置 - Place
放置於絕對位置 - Grid
放置於陣列的指定位置 - Method
- After
延遲方法,在給定的秒數後執行function,可用來模擬while迴圈,以下是讓Label達成每秒刷新的範例def update_clock(self):
now = time.strftime("%H:%M:%S")
label1.configure(text=now)
window.after(1000, update_clock)
JSON 是一種輕量級資料交換格式。其內容由屬性和值所組成,因此也有易於閱讀和處理的優勢。Python 可透過 json 模組夠將其解析和字串化。
- json.load
用來讀取(反序列化) Json 格式的資料,通常搭配 open() with read mode 使用。 - json.dump
用來將資料寫入(序列化) Json格式的檔案,通常搭配open() with write mode 使用
沒有留言:
張貼留言