# 2024-03-02 中央大學 Python基礎班 上課紀錄 ## 2024-03-16 #### 變數命名規則 ##### 變數命名規則 1. 可以使用英文字母大寫小寫、數字和底線。 > 例如:`a`和`A`是不同的變數名稱。 2. 可以使用數字,但第一個字不能是數字。 > 例如:`1abc`為錯誤命名,`abc1`為合法名字。 3. 大小寫代表不同的變數。 > 例如: > > - 底線開頭的變數通常為隱藏的變數,不打算給外部使用。 > - 開頭連續兩個底線的變數,代表其唯一性,不可被修改。 4. 不可以使用保留字。 > 保留字: > > If、elif、else、and、or、not、import、from、as、assert、for、while、break、continue、try、except、finally、pass、def、return、lambda、del、global、nonlocal、in、is、with、yield、class、None、True、False #### 函式 ```python= # 函式內的程式碼必須要通過呼叫才會被執行 def show_hello(): print('Hello world') show_hello() # 呼叫show_hello函式 show_hello() # 呼叫show_hello函式 ``` #### 查python有哪些關鍵字 ```python= help('keywords') import keyword print(keyword.kwlist) ``` #### 9的99乘法表函式 ```python= def nine_nine(): for n in range(1, 10): print(f'9 x {n} = {9 * n}') nine_nine() ``` #### 參數 ```python= def caln(n): print(n ** 2) caln(5) caln(11) ``` #### 兩個參數 ```python= def plus(n1, n2): print(n1 + n2) plus(3, 8) plus(599, 877) ``` ```python= def show(a, b, c, d, e): print(a) print(b) print(c) print(d) print(e) show(1, 'Hi', True, 90, 54) ``` #### 多次呼叫 ```python= def plus(n1, n2): # print(n1 + n2) return n1 + n2 # 66, 77, 88, 99 a = plus(66, 77) b = plus(88, 99) c = plus(a, b) print(f'a = {a}') print(f'b = {b}') print(f'c = {c}') ``` #### 寫一含式`gen_num`,傳入兩個參數,產生該參數之間的連續數字後,回傳tuple ``` def gen_num(n1, n2): return tuple(range(n1, n2 + 1)) print( gen_num(25, 30) ) ``` #### 寫一含式`gen_num`,傳入兩個參數,產生該參數之間的連續數字後,回傳用`-`符號隔開的字串 例如傳入`3`和`9`兩個數字,會得到`3-4-5-6-7-8-9`字串 #### 一般寫法 ```python= def gen_num(n1, n2): # 產生連續數字 all_num = list(range(n1, n2 + 1)) new_num = [] for n in all_num: new_num.append(str(n)) # 轉型後新增到新的list new_str = '-'.join(new_num) # 將 - 符號加入new_num list內的每一個元素之間 return new_str print(gen_num(2, 5)) ``` #### 參數預設值 ```python= def show_me(name, age, phone = '沒留電話', addr= 'xxx'): # 有預設值的參數,其右邊所有參數都必須要有預設值 print(f'你的名字: {name}, 年齡: {age}, 電話: {phone}, 地址: {addr}') show_me('aaron', 99, '這是地址') ``` #### 指定參數 ```python= def show_me(name, age, phone = '沒留電話', addr= 'xxx'): # 有預設值的參數,其右邊所有參數都必須要有預設值 print(f'你的名字: {name}, 年齡: {age}, 電話: {phone}, 地址: {addr}') show_me('test', age = 99, name = 'aaron', addr = '這是地址') ``` ```python= print('Hello', 'World', end='', sep='-') print('Hello', 'Python') ``` #### 單行寫法 ```python= def gen_num(n1, n2): return '-'.join([str(n) for n in range(n1, n2 + 1)]) print( gen_num(25, 30) ) print( gen_num(1, 11) ) ``` #### 一級函式 ```python= def show_me(name, age): print(f'name = {name}, age = {age}') return '有return' def show_you(name, age): print(f'you are {name}, your age is {age}') show_me('aaron', 99) a = show_me('ok', 9) b = show_me # 一級函式 print(a) print(b) b('hello', 88) def show_me_twice(f, name, age): f(name, age) f(name, age) show_me_twice(show_me, 'aaron', 99) show_me_twice(show_you, 'aaron', 99) ``` #### swap ```python= def swap(n1, n2): return n2, n1 # 打包(n2, n1) a = 3 b = 5 a, b = swap(a, b) # 解包 print(a) print(b) ``` #### lambda ``` #def swap(n1, n2): # return n2, n1 # 打包(n2, n1) swap = lambda n1, n2: (n2, n1) a = 3 b = 5 a, b = swap(a, b) # 解包 print(a) print(b) ``` ``` #def plus(n1, n2): # return n1 + n2 plus = lambda n1, n2: n1 + n2 print(plus(2, 3)) ``` #### lambda應用 ``` # def join_me(sep, data): # result = sep.join(data) # return result join_me = lambda sep, data: sep.join(data) a = join_me('-', ['aaron', 'andy']) print(a) ``` #### 濃縮極致版 ``` print( (lambda sep, data: sep.join(data))('-', ['aaron', 'andy']) ) ``` #### 模組 python.py ``` import hello as hello from hello import mux b = hello.plus(3, 4) print(b) print(hello.abc) print(mux(4, 5)) ``` hello.py ``` def plus(a, b): return a + b def min(a, b): return a - b def mux(a, b): return a * b def div(a, b): return a - b abc = 'Hello module' if __name__ == '__main__': print('我被直接執行') ``` #### 練習 ```python= a = [(2, 3, 4), [6, (99, 0, 4, [2]), 0], 88] print(a[1][1][3][0]) ``` #### dict ```python= a = {'a':99, 77:'aaron'} print(a['a']) print(a[77]) # 取資料 a[77] = 'apple' # 改資料 print(a[77]) print(a) a['ok'] = 888 # 新增資料 print(a) del a[77] # 刪除資料 print(a) ``` #### 資料轉換 ```python= a = {'a': [10, 20, 30]} for n in a.keys(): r = [] r.append(n) r.extend(a[n]) print(r) ``` #### callable ```python= def abc(): print('abc被呼叫了') pass print( callable(abc) ) abc = 8 print( callable(abc) ) # if callable(abc): abc() ``` #### 不定長度參數 ```python= def super_plus(*args): print(sum(args)) super_plus(1, 2, 3) super_plus(1, 2, 3, 4, 5) super_plus(1, 2, 3, 4, 5, 6, 7) ``` ```python= def p(*args, ok): print(args) print(ok) p(1, 2, 3, ok = 9) ``` #### 學生成績管理系統 ```python= import csv grades = {} # 空的字典 def query_by_name(): name = input('請輸入要查詢的姓名: ') if name in grades: print(f'姓名: {grades[name]}, 學號: {grades[name][0]}, 國文: {grades[name][1]}, 英文: {grades[name][2]}, 數學: {grades[name][3]}') else: print('查無此人') def query_all(): for name in grades: print(f'姓名: {name}, 學號: {grades[name][0]}, 國文: {grades[name][1]}, 英文: {grades[name][2]}, 數學: {grades[name][3]}') def del_grade(): name = input('請輸入要刪除的學生姓名: ') if name in grades: # 判斷name有沒有存在字典裡面的key del grades[name] save() print('目前資料: ', grades) # 從csv把資料讀回grades字典 def load(): try: with open('student_system.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) # 跳過第一列 next(reader) for row in reader: # 每次讀取一筆資料,且資料為list格式 grades[row[0]] = row[1:] print('讀回來的資料: ', grades) # 測試用 except FileNotFoundError: print('尚無資料,不讀取') # 將grades字典存檔成csv def save(): # 打開檔案 with open('student_system.csv', 'w', encoding='utf-8', newline='') as file: writer = csv.writer(file) # 使用檔案物件建立csv寫入器 # 寫入list到檔案去 writer.writerow(['姓名','學號','國文','英文','數學']) for key in grades: # 將dict資料攤平成list data = [key] data.extend(grades[key]) writer.writerow(data) def add_grade(): name = input('請輸入姓名: ') no = input('請輸入學號: ') mandrin = input('請輸入國文成績: ') english = input('請輸入英文成績: ') math = input('請輸入數學成績: ') # 新增一筆資料到字典 grades[name] = [no, mandrin, english, math] # 存檔 save() print('新增完成.', grades) def management(): while True: print('----------------------------') print('管理學生成績') print('----------------------------') print('1. 新增學生成績') print('2. 刪除學生成績') print('3. 回主選單') user_input = input('=> ') if user_input == '1': add_grade() elif user_input == '2': del_grade() else: break def query(): while True: print('----------------------------') print('查詢學生成績') print('----------------------------') print('1. 查詢全部成績') print('2. 姓名查詢成績') print('3. 回主選單') user_input = input('=> ') if user_input == '1': query_all() elif user_input == '2': query_by_name() else: break def student_system(): load() while True: print('--------------------------------------') print('學生成績管理系統') print('版本: 0.01') print('--------------------------------------') print('1. 管理學生成績') print('2. 查詢學生成績') print('3. 離開') user_input = input('=> ') if user_input == '1': management() elif user_input == '2': query() else: break student_system() ``` ## 2024-03-09 ```python= # 寫一個程式,輸入三個數字,加總後,顯示在終端機上 a = input('請輸入第一個數字: ') a = int(a) b = input('請輸入第二個數字: ') b = int(b) c = int( input('請輸入第三個數字: ') ) total = a + b + c print(f'總和為: {total}') ``` #### 迴圈寫法 ``` # 寫一個程式,輸入三個數字,加總後,顯示在終端機上 all_num = [] for n in range(3): all_num.append( int( input(f'請輸入第{n + 1}個數字: ') ) ) print( sum(all_num) ) ``` 另一種寫法: ``` total = 0 for n in range(1, 4): a = int(input(f'請輸入第{n}個數字: ')) total = total + a print(total) ``` ##### 寫一個程式,輸入任意個數字,加總後,顯示在終端機上 ```python= # 寫一個程式,輸入任意個數字,加總後,顯示在終端機上 total = 0 for n in range(10000): a = input(f'請輸入第{n + 1}個數字(輸入quit離開): ') if a == 'quit': # 直接結束迴圈 break else: a = int(a) total = total + a print(total) ``` `while`迴圈寫法(無窮迴圈): ```python= # 寫一個程式,輸入任意個數字,加總後,顯示在終端機上 total = 0 n = 1 while True: a = input(f'請輸入第{n}個數字(輸入quit離開): ') if a == 'quit': # 直接結束迴圈 break else: a = int(a) total = total + a n += 1 print(total) ``` #### `elif` ```python= import datetime # 取得今天的日期物件 t = datetime.date.today() w = t.weekday() # 得到今天是星期幾 print(w) # 0 = 星期一.....星期六 = 5, 星期日 = 6 if w == 0: # 星期一 print('星期一: 今天適合穿紅色') elif w == 1: # 星期二 print('星期二: 今天適合穿藍色') elif w == 2: # 星期三 print('星期三: 今天適合穿黃色') elif w == 3: # 星期四 print('星期四: 今天適合穿綠色') elif w == 4: # 星期五 print('星期五: 今天適合穿紫色') elif w == 5: # 星期六 print('星期六: 今天適合穿粉色') elif w == 6: # 星期日 print('星期日: 今天適合穿彩色') ``` ##### 隨機數 ```python= import random # 隨機產生0~4之間的整數 a = random.randint(0, 39) print(a) if a == 0: print('今天會撿到錢') elif a == 1: print('今天中彩卷') elif a == 2: print('今天會加薪') elif a == 3: print('今天發獎金') elif a == 4: print('今天中統一發票') else: print('沒中') ``` #### `match-case`寫法 ```python= import random # 隨機產生0~4之間的整數 a = random.randint(0, 39) print(a) match a: case 0: print('今天會撿到錢') case 1: print('今天中彩卷') case 2: print('今天會加薪') case 3: print('今天發獎金') case 4: print('今天中統一發票') case _: print('沒中') ``` #### 剪刀石頭布 ```python= import random # 電腦出拳 pc = random.randint(0, 2) # 0=剪刀, 1=石頭, 2=布 print(f'電腦出了: {['剪刀', '石頭', '布'][pc]}') # 玩家出拳 user = int(input('請猜拳(0=剪刀, 1=石頭, 2=布): ')) # 比輸贏 if pc == 0 and user == 1: print('你贏了') elif pc == 0 and user == 2: print('你輸了') elif pc == 1 and user == 0: print('你輸了') elif pc == 1 and user == 2: print('你贏了') elif pc == 2 and user == 0: print('你贏了') elif pc == 2 and user == 1: print('你輸了') else: print('平手') ``` ##### 拿到`[6, 4, 2]` ```python= a = [1,2,3,4,5,6, 7, 8, 9] print(a[-4::-2]) ``` > **注意:** > 如果step為-1的時候,start不能比end小 ##### 計算活動參加人數 ```python= a = set() # 建立空的set a.add(3) a.add(3) a.add(3) a.add(4) a.add(5) a.remove(5) a.remove(4) a.remove(3) print(type(a)) print(a) a = ['aaron', 'andy', 'apple', 'abner', 'aaron', 'alan', 'apple', 'ana', 'aaron', 'alan'] a = set(a) print(f'今天總共 {len(a)} 人參加活動') ``` #### set運算 ```python= employee1 = {'英語', '日語', '粵語', '台語'} employee2 = {'法語', '德語', '中文', '日語', '台語'} # emp1會,但是emp2不會的語言 print(employee1 - employee2) # 差集 # emp2會,但是emp1不會的語言 print(employee2 - employee1) # 差集 # 兩個人都會的語言 print(employee1 & employee2) # 交集 # 兩個人會哪些語言 print(employee1 | employee2) # 聯集 # 只有一個人會的語言 print(employee1 ^ employee2) # 對稱差集 ``` #### ```python= a = [2, 4, 6, 8] b = [] for n in a: b.append(n*n) print(b) ``` ``` a = [2, 4, 6, 8] print([n*n for n in a]) ``` ##### 加20分(使用for comprehension) ```python= data = [] while True: temp = input('請輸入成績(quit=離開): ') if temp == 'quit': break else: data.append(int(temp)) print([n + 20 for n in data]) ``` ##### 單行if ```python= import random pc = random.randint(1, 5) print(f'答案: {pc}') user = int(input('請猜一個數字1~5之間: ')) if pc == user: print('猜對了') else: print('猜錯了') print('猜對了') if pc == user else print('猜錯了') ``` #### 單行if + for comprehension ```python= data = [] while True: temp = input('請輸入成績(quit=離開): ') if temp == 'quit': break else: data.append(int(temp)) # start data_new = [] for n in data: if n < 60: data_new.append(n + 20) else: data_new.append(n) print(data_new) # end print([n + 20 if n < 60 else n for n in data]) ``` #### 過濾資料 ```python= print([n + 20 if n < 60 else n for n in data]) ``` #### 捕捉例外 ```python= try: a = [] print(a[1]) a = int(input('請輸入一個數字: ')) print(f'你輸入的數字是: {a}') except ValueError: print('不正確的輸入,掰掰') except IndexError: print('資料索引有問題') ``` #### tuple ```python= # a = (1, 2, 3) a = 1, 2, 3, # 打包pack # a = 1, print(a) a, b, c = a # 解包unpack print(a) print(b) print(c) # print(a[0]) print(type(a)) a = (4, 5, 6, 7, 8) a1, *a2, a3 = a print(a1) print(a2) print(a3) ``` #### 猜數字 ```python= import random a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] answer = random.sample(a, 4) # 隨機挑出四筆資料 answer = ''.join(answer) # 將答案串接成一個字串 print(f'答案: {answer}') guess_count = 0 # 紀錄總共猜了幾次 while True: user = input('請猜0~9之間的四位數字(數字不可重複): ') guess_count += 1 print(f'已經猜了{guess_count}次') # 檢查是不是數字 try: int(user) except ValueError: print('只能輸入數字, 請重新輸入.') continue # 結束迴圈這一回合,剩下的程式碼都不會執行,直接回到迴圈開頭進行下一回合 # 檢查是不是四個數字 if len(user) != 4: print('只能輸入四個數字,請重新輸入') continue # 檢查數字有沒有重複 if len(set(user)) != 4: print('數字不可以重複,請重新輸入') continue # 猜對了,遊戲結束 if answer == user: print(f'猜對了,總共猜了{guess_count}次, 遊戲結束.') break # 判斷有幾個A how_main_A = 0 if answer[0] == user[0]: how_main_A += 1 if answer[1] == user[1]: how_main_A += 1 if answer[2] == user[2]: how_main_A += 1 if answer[3] == user[3]: how_main_A += 1 # 判斷有幾個B how_main_B = 0 if user[0] in answer and user[0] != answer[0]: how_main_B += 1 if user[1] in answer and user[1] != answer[1]: how_main_B += 1 if user[2] in answer and user[2] != answer[2]: how_main_B += 1 if user[3] in answer and user[3] != answer[3]: how_main_B += 1 print(f'{how_main_A}A{how_main_B}B') ``` ## 2024-03-02 ## 安裝開發環境 1. 安裝Visual Studo Code (搜尋關鍵字: vsCode) 2. 安裝Python SDK(搜尋關鍵字: python) 3. 安裝Python extension(VSCode會問你需不需要安裝) ## 快速鍵 1. Ctrl-F5: 執行Python程式 2. Ctrl-Shift-N: 建立新資料夾 3. Ctrl-S: 儲存程式碼 4. Ctrl-Shift-P: 打開VSCode的功能清單 ## 第一個程式 ```python= print('123') print('456') print('789') input() input() # 輸入 # 輸入 a = input() b = input() # 輸出 print(a, end='') # \n = 換行 print(b) # Ctrl-/: 註解程式碼 print(a, b, a, b, sep='xxxxx') # 每一個參數的分隔字 ``` ```python= print('123' + '1') # str 字串型態 print(123 + 1) # int 字串型態 a = type(999) print(a) a = type('999') print(a) print(type(True)) a = input('請輸入第一個數字: ') b = input('請輸入第二個數字: ') # 將輸入的字串轉型為數字 a = int(a) b = int(b) print('加總後為: ', a + b) ``` > **備註:** > `int()`: 將字串轉型成數字 > `str()`: 將數字轉型成字串 ## 四則運算 ``` print(3 ** 2) print(3 ** 3) print(2 ** 5) print(7 // 2) print(7 % 2) print(99 // 7) print(99 % 7) ``` ``` print(3 > 4) # False print(3 < 4) # True print(3 >= 4) # False print(3 <= 4) # True print(3 == 4) # False print(3 != 4) # True print(32 == 32) print(32 != 32) print('1' == '1') ``` #### 判斷分數有沒有及格 ```python= a = input('請輸入你的成績: ') a = int(a) # 轉型成數字 if a >= 60: print('及格') else: print('不及格') ``` #### 搜尋文字 ```python= a = input('請輸入要被搜尋的文章: ') b = input('請輸入關鍵字: ') if b in a: print(b, '有出現在文章內') else: print(b, '沒有出現在文章內') ``` #### 判斷奇偶數 ```python= a = input('請輸入數字: ') a = int(a) if a % 2 == 0: print('偶數') else: print('奇數') ``` #### 數字加總 ```python= a = int( input('請輸入第1個數字: ') ) b = int( input('請輸入第2個數字: ') ) c = int( input('請輸入第3個數字: ') ) a += b # a變數跟b變數相加後存回a變數 a += c # a變數跟c變數相加後存回a變數 print('加總後=', a) ``` #### list ```python= a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # 編號從0開始 # 查詢 print(a[0]) print(a[8]) # 修改 a[5] = 99 # 新增 a.append(8) a.append('aaron') # 插入 a.insert(0, 'test') # 刪除 a.remove(99) # 指定位置刪除 del a[5] print(a) ``` #### for-in ```python= a = [1, 2, 3, 4, 5, 9, 19] sum = 0 for t in a: sum += t print(sum) ``` #### 階乘 ```python= a = int(input('請輸入階乘數: ')) sum = 1 for t in range(2, a + 1): sum *= t print(a, '的階乘為: ', sum) ``` #### 格式化字串 ```python= name = input('請輸入姓名:') age = input('請輸入年齡:') print('你的名字:', name, ', 年齡: ', age, '歲') # 格式化字串 print(f'你的名字: {name + 'ho'}, 年齡: {age}歲') # f字串 ``` #### 取得ubike資料 ```python= import requests import csv url = 'https://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv' # 取得ubike資料csv resp = requests.get(url) # 成功 if resp.status_code == 200: rows = resp.text.splitlines() # 將csv資料轉成兩層的list data = list( csv.reader(rows) ) user = input('請輸入要搜尋的站名: ') for t in data: if user in t[3]: print(f'站名: {t[3]}, 地址: {t[6]}') print(f' - 可借: {t[12]}') print(f' - 可還: {t[5]}') print(f' - 總數: {t[10]}') print() else: print('無法取得ubike資料') ```