# 2023-08-05 Python入門班 ## 2023-08-19 #### 學生成績管理系統 ```python= # 學生成績管理系統 # 主功能: # 1. 管理學生成績 # - 新增學生成績 # - 刪除學生成績 # 2. 查詢學生成績 # - 依姓名查詢 # - 查詢全部 # # (資料存檔,資料讀取,CSV格式) import csv # 存放所有成績用的字典dict grades = {} # 主程式 def student_system(): # 讀檔 try: load() except FileNotFoundError: print('找不到資料庫檔案') except: print('讀取資料庫失敗') while True: print('--------------------------') print('學生成績管理系統') print('--------------------------') print('1. 管理學生成績') print('2. 查詢學生成績') print('3. 結束系統') user_input = input('=> ') # 等待使用者輸入 if user_input == '1': # 管理學生成績 management() elif user_input == '2': # 查詢學生成績 query() elif user_input == '3': print('掰掰') break else: print('無效的輸入') # 管理學生成績 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() elif user_input == '3': break else: print('錯誤的輸入') # 新增一筆學生成績 def add_grade(): name = input('請輸入學生姓名:') no = input('請輸入學號:') mandrain = int(input('請輸入國文成績:')) english = int(input('請輸入英文成績:')) math = int(input('請輸入數學成績:')) # 將資料新增到字典 grades[name] = [no, mandrain, english, math] # 存檔 save() print('新增完成') print(grades) # 開發中測試用 # 刪除一筆學生成績 def del_grade(): name = input('請輸入要刪除的學生姓名:') if name in grades: del grades[name] # 從字典刪除一筆資料 save() # 存檔 print('刪除完成') else: print('查無此人') # 查詢學生成績 def query(): while True: print('--------------------') print('查詢學生成績') print('--------------------') print('1. 依姓名查詢') print('2. 查詢全部成績') print('3. 回主功能表') user_input = input('=> ') if user_input == '1': query_by_name() elif user_input == '2': query_all() elif user_input == '3': break # 離開查詢學生成績 else: print('輸入錯誤') # 依姓名查詢成績 def query_by_name(): name = input('請輸入學生姓名: ') if name in grades: print(f'姓名: {name}, 學號: {grades[name][0]}, 國文: {grades[name][1]}' + f', 英文: {grades[name][2]}, 數學: {grades[name][3]}') else: print('查無此人') # 查詢全部成績 def query_all(): for name in grades: print(f'姓名: {name}, 學號: {grades[name][0]}, 國文: {grades[name][1]}' + f', 英文: {grades[name][2]}, 數學: {grades[name][3]}') # 存檔 def save(): with open('student_system.csv', 'w', encoding='utf-8', newline='') as file: # 取得csv寫入物件 writer = csv.writer(file) # 寫入標題 writer.writerow(['姓名', '學號', '國文', '英文', '數學']) # 寫入所有成績資料 for key in grades: data = [key] data.extend(grades[key]) # 將dict資料轉成list writer.writerow(data) # 寫入一筆資料到csv # 讀檔 def load(): with open('student_system.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) next(reader) # 跳過第一行不要讀取 for row in reader: grades[row[0]] = row[1:] print(grades) # 測試用 # 執行系統 student_system() ``` #### 類別與物件 ```python= # 定義類別Car class Car: # 方法method def show(self): print(f'我是車子, 汽油: {self.gas}公升, 顏色: {self.color}色') def add_gas(self, gas): self.gas = gas # self.gas稱為屬性attribute print(f'加油{gas}公升') def set_color(self, color): self.color = color print(f'顏色設定為{color}色') # 建構式 def __init__(self): self.gas = 0 self.color = '白' print('我是特殊的__init__') def __str__(self): return f'我是車子, 汽油: {self.gas}公升, 顏色: {self.color}色' car = Car() # 透過Car類別建立物件並存到car變數中 car.show() # 呼叫Car物件裡面的show方法 car.add_gas(20) car.set_color('紅') print(car) ``` #### 模組 ###### a12.py ```python= # 1. py程式碼檔案,就是一個模組 # 2. 模組裡面的程式碼一經import就會直接被執行 # 3. 模組的檔名命名需要根據變數命名規則,否則會無法被import # 4. PEP 8建議模組命名請用全小寫,除非加底線可以增加閱讀性,否則不需要加底線 tag = 'my plus module' def max(a, b): return a if a > b else b def min(a, b): return a if a < b else b a = 3 b = 7 if __name__ == '__main__': print(f'{a}, {b} max = {max(a, b)}') print(f'{a}, {b} min = {min(a, b)}') print(__name__) ``` ###### test.py ```python= import jlfkjsadlkfjlasdkflasdhfkjasdhfhfkdjhakjdfhkasfdhkadhfkahafldhfkadahf as t t.show_me() import a12 print(a12.max(77, 99)) print(a12.min(77, 99)) print(a12.tag) from a12 import max, min, tag print(max(33, 77)) print(min(33, 77)) print(tag) ``` #### lambda應用 ```python= a = [34, 22, 13, 79, 5] # 1. 請使用lambda寫一個函式,傳入一個list後,回傳該list內的偶數 print( (lambda my_list: [x for x in my_list if x % 2 == 0])(a)) # 2. 請使用lambda寫一個函式,傳入一個list後,回傳該list內的奇數加總 print( (lambda my_list: sum([x for x in my_list if x % 2 == 1]) )(a)) ``` #### lambda ```python= scores = [34, 65, 98, 100, 23, 45, 87, 66] # 當分數小於60, 回傳True代表該筆資料要保留 result = list( filter(lambda x: x < 60, scores) ) # filter過濾資料 print(result) result = list( map(lambda x: x + 30 if x < 60 else x, scores) ) # map用來轉換資料 print(result) print( (lambda a, b: a ** b)(2, 2) ) ``` #### `filetr`和`map` ```python= scores = [34, 65, 98, 100, 23, 45, 87, 66] # 當分數小於60, 回傳True代表該筆資料要保留 def filter_func(x): return x < 60 result = list( filter(filter_func, scores) ) # filter過濾資料 print(result) def map_func(x): return x + 30 if x < 60 else x result = list( map(map_func, scores) ) # map用來轉換資料 print(result) ``` #### 一級函式 ```python= # 一級函式 def plus(a, b): print(f'{a} + {b} = {a + b}') plus(1, 2) # 函式名稱後面有小括號叫做:函式呼叫 a = plus a(3, 4) plus(4, 5) print(type(a)) ``` #### 不定長度參數 ```python= # 不定長度參數 # 如果除了不定長度參數之外還有其他參數,則必須使用指定參數的方式傳資料給參數 # 寫一函式,可以傳入多個數字,加總後回傳 def sum(*args, test, show=0): print(test, show) total = 0 for a in args: total += a return total print( sum(1, 2, 3, 4, test=999) ) print( sum(1, 2, 3, 4, 5, 6, 7, 8, test=123) ) print( sum(1, 2, test='aaron', show='show') ) # 不定長度參數dict def show_info(**userinfo): print(userinfo) # 因為是兩個星星的不定長度參數,所以提供參數時全部都必須使用指定參數的方式 show_info(name='aaron', age=19, city='台北市', phone='0988765432', h=170, w=22) ``` #### 指定參數 ```python= # 指定參數,讓參數傳遞時可以不用依照順序 def show_info(name, age, address, phone, height, weight): print(f'Name: {name}') print(f'Age: {age}') print(f'address: {address}') print(f'phone: {phone}') print(f'height: {height}') print(f'weight: {weight}') show_info('aaron', 19, '桃園市中壢區', 333999, weight=22, height=170) print('aaron', end='') ``` #### 參數預設值 ```python= # 筆記網址: https://hackmd.io/@aaronlife/ncu-python-20230805 # 函式預設參數 # 1. 有預設的參數右邊的所有參數都需要有預設值 def show_me(name='無名氏', age=0): # 0 為age預設值 print(f'I am {name}, I am {age} years old') show_me('aaron', 18) show_me(77) ``` #### 補充: pack與unpack ```python= a = 1, 2, 3 # tuple print(type(a)) # print(a[0]) # print(a[1]) # print(a[2]) a1, a2, a3 = a # unpack解包 print(a1) print(a2) print(a3) ``` #### 函式回傳值 ```python= # 函式回傳值 def plus(a, b): print(f'{a} + {b} = {a + b}') return a + b # 回傳a + b的結果 s1 = plus(1, 2) s2 = plus(3, 4) print(f's1 = {s1}, s2 = {s2}') # 寫一函式swap, 傳入a, b兩個參數後以顛倒的順序回傳 # 例: 傳入3, 4後回傳 4, 3 def swap(a, b): return b, a first = 10 second = 20 print(swap(2, 3)) first, second = swap(first, second) print(f'first={first}, second={second}') ``` #### 函式參數 ```python= # 該函式須提供name參數 def show_me(name): print(f'你的名字是{name}') show_me('aaron') show_me('andy') # 加法的函式, 該函式需要兩個參數,少一個都不行 # 參數相當於變數,只是他是該函式專屬的變數,函式外面無法使用 def plus(a, b): print(f'{a}和{b}的總和為: {a + b}') plus(1, 2) plus(999, 888) # 寫一個函式mux,傳入四個參數,傳入後計算乘積後顯示出來 def mux(a, b, c, d): print(f'{a}x{b}x{c}x{d} = {a * b * c * d}') mux(2, 3, 4, 5) mux(12, 2, 3, 9) ``` #### 函式 ```python= import time import keyword print(keyword.kwlist) # python的保留字/關鍵字 # 函式 # 1. 英文大小寫,數字,底線 # 2. 名稱第一個字不可以是數字 # 3. 不可以使用python保留字/關鍵字 # 1. 函式的程式碼必須縮排 # 2. 函式必須經過[呼叫]的手段才會被執行 def analyze_name(): user = input('請輸入你的姓名:') print('分析姓名中....') time.sleep(1.5) print('分析運勢中....') time.sleep(2) print('分析完成') time.sleep(1) print('您的名字帶金,富貴命') print('需小心職場上的鬥爭') analyze_name() # 函式呼叫 analyze_name() # 函式呼叫 analyze_name() # 函式呼叫 ``` ## 2023-08-12 #### `set` `dict` ```python= data = [1, 2, 3, 4, 5, 6, 7, 8] data.append(1) data.append(1) data.append(1) data.remove(8) del data[0] # print(data) # list取值 my_set = {1, 2, 3, 4, 5, 6, 7, 8} # 1. 無序的群集資料結構 # 2. 資料不會重複 my_set.add(1) my_set.add(1) my_set.add(1) my_set.remove(8) # print(my_set) new_set = set() for s in my_set: new_set.add(s ** 2) # print(new_set) a1 = {1, 2, 3, 4} a2 = {3, 4, 5, 6} # print(a1 - a2) # 差集,將左右兩邊都出現的資料從左邊的set移除 # print(a1 & a2) # 交集(and, inner),保留兩邊都有出現的資料 # print(a1 | a2) # 聯集(or, outer),將全部的資料合併,但重複的資料只會保留一份 # print(a1 ^ a2) # 對稱差集,將兩邊重複的資料去掉,只保留不重複的資料 # dict 字典 key:value a = {'a': 999, 0: 'test', False: 888, 1: 'Hello', 1: 'aaron', 1: 'ok', True: False, True: 'Hello'} # print(a['a']) # print(a[777]) # print(a[True]) # print(a[1]) # print(int(False)) a[1] = 'test' # 修改字典裏面的某一筆資料 print(a[1]) a[55] = 'ookk' # 新增資料 del a[1] # 刪除key為1的該筆資料 for b in a: print(b, '=', a[b]) if 0 in a: print('key存在') print(a['aaron']) else: print('key不存在') a = '中壢火車站' if '中' in a: print('中有在', a, '字串內出現過') else: print('中沒有在', a, '字串內出現過') ``` #### `tuple`,打包,解包 ```python= # tuple # 資料不可修改,其餘跟list一樣 a = (1, 2, 3, 4) # a[0] = 9 # print(a[0]) b = 1, 2, 3, 4 # 打包成tuple b = set() # 建立空的set b = 4, print(b, type(b)) # 打包(pack),解包(unpack) a = 1, 2, 3, 4, 5, # 打包 print(a) a1, a2, a3, a4, a5 = a print(a1) print(a2) print(a3) print(a4) print(a5) # b = 'andy', 'aaron', 'apple', 'alan', 'abner' print(b) b_best, b2, b_ignore, *b_bottom = b print(b_best) print(b2) print(b_ignore) print(b_bottom) ``` #### 猜拳遊戲 ```python= # 猜拳遊戲 # 0=剪刀, 1=石頭, 2=布 import random game_mssage = ['剪刀', '石頭', '布'] # 電腦出拳 pc = random.randint(0, 2) print(f'電腦出: {game_mssage[pc]}') # 測試用 # 玩家出拳 player = int(input('請出拳(0=剪刀, 1=石頭, 2=布): ')) print(f'你出了: {game_mssage[player]}') if pc == 0 and player == 1: # 電腦=剪刀, 玩家=石頭 print('你贏了') elif pc == 0 and player == 2: # 電腦=剪刀, 玩家=布 print('你輸了') elif pc == 1 and player == 0: # 電腦=石頭, 玩家=剪刀 print('你輸了') elif pc == 1 and player == 2: # 電腦=石頭, 玩家=布 print('你贏了') elif pc == 2 and player == 0: # 電腦=布, 玩家=剪刀 print('你贏了') elif pc == 2 and player == 1: # 電腦=布, 玩家=石頭 print('你輸了') else: print('平手') ``` #### 索引切片 ```python= # 索引切片 : # start:end:step(不包含) a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # print( a[ 0 : 3 ] ) # 取得第1筆到第3筆 # print( a[ : 3 ] ) # 取得第1筆到第3筆 # print( a[ 3 : 6 ] ) # 取得第4筆到第6筆 # print( a[ 2 : 10] ) # 取得第3筆到第10筆 # print( a[ 2 : ] ) # 取得第3筆到最後1筆 # print( a[ : ] ) # 取得第1筆到最後1筆 # print( a[ -1 ] ) # 取得最後1筆 # print( a[ 7 : 10] ) # 取得第8筆到第10筆 # print( a[ -3: ] ) # 取得倒數第3筆到最後1筆 # print( a[ 0 : 10 : 2 ] ) # 取第1 3 5 7 9筆 # print( a[ : : 2 ] ) # 取第1 3 5 7 9筆 # print( a[ 1 : : 2 ] ) # 取第2 4 6 8 10筆 # print( a[ : : -1 ] ) # # print( a[ -4: -7 : -1 ] ) # 取得 [6, 5, 4] # print( a[ 6 : 3 : -1 ] ) # 取得 [6, 5, 4] # print( a[ -2: : -3 ] ) # 取得 [8, 5, 2] # range() 產生一段連續數字 a = range(3) # range(0, 3) a = range(0, 10) # [:10] a = range(3, 13) # 3~12 a = range(1, 10, 2) # 1, 3, 5, 7, 9 a = range(6, 3, -1) # 6, 5, 4 a = range(0, -10, -1) # 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 print(list(a)) # range是for-in的好朋友 for i in range(10): print('*', end='') ``` #### `range()` ```python= import random # 產生1~10之間的數字 answer = random.randint(1, 10) print(f'答案: {answer}') # 測試 for i in range(3): user = int(input(f'請猜一個1~10之間的數字(第{i + 1}次): ')) if user == answer: # 猜對了 print('猜對了') # 強制結束迴圈 break else: print('猜錯') ``` #### 九九乘法表+兩層迴圈 ```python= # 寫出2的九九乘法表 # 2 x 1 = 2 # 2 x 2 = 4 # 2 x 3 = 6 # 2 x 4 = 8 # 2 x 5 = 10 # 2 x 6 = 12 # 2 x 7 = 14 # 2 x 8 = 16 # 2 x 9 = 18 # 完整九九乘法表 for j in range(2, 10): for i in range(1, 10): print(f'{j} x {i} = {j * i}') ``` #### 例外捕捉+while迴圈 ```python= # while # 語法: # while 條件式: # 程式碼1 # 程式碼2 # 程式碼3 # ... a = 0 data = [] while True: user = input('請輸入數字(輸入quit結束輸入): ') if user == 'quit': break else: # data.append(user) # try-except 捕捉例外 try: data.append(int(user)) except ValueError: # 發生例外ValueError print('輸入的資料不是數字,請重新輸入') print(data) # 數字加總 # print(sum([int(n) for n in data])) print( sum(data) ) ``` #### `continue` ```python= # break: 直接結束迴圈 # continue: 忽略這次剩下的程式碼,重頭開始進行下一次迴圈 scores = [22, 45, 78, 32, 93, 100] for n in scores: if n >= 60: # 及格 continue print(n) # 印出不及格的 ``` #### 大樂透模擬兌獎程式 ```python= # 大樂透: 會從1~50挑出5個數字作為開獎號碼 # 讓使用者輸入5個數字,比對後告知中了甚麼獎 # 對中3個號碼=小獎 # 對中4個號碼=大獎 # 對中5個號碼=特獎 import random seed = list(range(1, 51)) # 產生1~50的數字 print(seed) bingo = random.sample(seed, 5) print(bingo) # 讓使用者輸入5個數字(for-comprehension版本) # user = [int(input(f'請輸入第{i}個號碼:')) for i in range(1, 6)] # 讓使用者輸入5個數字(for-in版本) # user = [] # for i in range(1, 6): # u = input(f'請輸入第{i}個數字:') # user.append(int(u)) user = [] i = 1 while i <= 5: u = input(f'請輸入第{i}個數字:') # 阻擋輸入非數字 try: int(u) except ValueError: print('輸入錯誤,請重新輸入!') continue # 阻擋重複數字 if int(u) in user: print('數字重複,請重新輸入') continue # 阻擋無效數字 # if int(u) < 1 or int(u) > 50: # if not (int(u) >= 1 and int(u) <=50): if not (1 <= int(u) <= 50): print('數字無效,需介於1~50之間,請重新輸入') continue user.append(int(u)) i += 1 print(user) # 紀錄猜中幾個數字 bingo_count = 0 # 比對使用者猜到幾個數字 for u in user: if u in bingo: bingo_count += 1 # 猜中數字 if bingo_count == 5: print('恭喜,特獎') elif bingo_count == 4: print('恭喜,大獎') elif bingo_count == 3: print('恭喜,小獎') else: print('沒中') ``` #### 猜數字遊戲 ```python= # 寫一遊戲,莊家從0~9之間挑出四個數字讓使用者猜 # 使用者必須猜4個不重覆數字 # 1. 如果使用者猜的數字有在莊家的答案內,但位置不同,莊家回回應B, 如果數字跟位置都猜中,莊嘉會回應A # 2. 例如: 答案=3248, 玩家猜=2398, 則為: 1A2B # 3. 4A則結束遊戲,接著莊家和玩家身分對調,最後以較少次數猜中對答案者為勝利 import random a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] answer = random.sample(a, 4) # answer = answer[0] + answer[1] + answer[2] + answer[3] answer = ''.join(answer) print(f'答案: {answer}') guess_count = 0 # 紀錄猜了幾次 while True: user = input('請猜0~9之間的四個數字(不可重複): ') guess_count += 1 # 猜的次數要加一 # 判斷是否輸入的是數字 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_many_A = 0 for i in range(4): if answer[i] == user[i]: how_many_A += 1 # if answer[0] == user[0]: # how_many_A += 1 # if answer[1] == user[1]: # how_many_A += 1 # if answer[2] == user[2]: # how_many_A += 1 # if answer[3] == user[3]: # how_many_A += 1 # 判斷幾個B how_many_B = 0 if user[0] in answer and user[0] != answer[0]: how_many_B += 1 if user[1] in answer and user[1] != answer[1]: how_many_B += 1 if user[2] in answer and user[2] != answer[2]: how_many_B += 1 if user[3] in answer and user[3] != answer[3]: how_many_B += 1 print(f'{how_many_A}A{how_many_B}B, 你已經猜了{guess_count}次') ``` ## 2023-08-05 #### 輸入 ```python= a = int( input('請輸入一個數字:') ) b = input('請再輸入一個數字:') # 將字串轉型成整數 b = int(b) print('剛剛輸入的數字:', a, '和', b) print('總和:', a + b) ``` #### 運算子 ```python= print(3 > 5) print(3 < 5) print(7 <= 9) print(4 >= 5) print(4 == 5) print(4 != 5) print(True and False) print(3 > 5 and 8 < 5) print(3 == 5 or 8 != 5) print(not 9 == 9) ``` #### 指派運算子 ``` a = 9 a %= 2 print(a) ``` #### 條件式 ``` a = 2 if a > 2: print('條件成立') else: print('條件不成立') ``` #### 練習 ``` # 寫一程式,使用者輸入一個數字,程式判斷後會顯示奇數或偶數 user_input = int(input('請輸入一個數字:')) if user_input % 2 == 1: print('奇數') else: print('偶數') ``` #### 成績判斷 ```python= # 成績判斷程式, 100分=滿分, 90~99=佳, 80~89=一般, 70~79=再努力 # 60~69=再加強, 不到60分=不及格 user_input = int(input('請輸入成績:')) if user_input == 100: print('滿分') if user_input >= 90 and user_input <= 99: print('佳') if user_input >= 80 and user_input <= 89: print('一般') if user_input >= 70 and user_input <= 79: print('再努力') if user_input >= 60 and user_input <= 69: print('再加強') if user_input < 60: print('不及格') ``` #### elif版本 ```python= # 成績判斷程式, 100分=滿分, 90~99=佳, 80~89=一般, 70~79=再努力 # 60~69=再加強, 不到60分=不及格 user_input = int(input('請輸入成績:')) if user_input == 100: print('滿分') elif user_input >= 90 and user_input <= 99: print('佳') elif user_input >= 80 and user_input <= 89: print('一般') elif user_input >= 70 and user_input <= 79: print('再努力') elif user_input >= 60 and user_input <= 69: print('再加強') # 上面的判斷式全部都不成立,就會執行else的程式碼 else: print('不及格') ``` #### 隨機數 ```python= import random # 隨機產生0~9之間的整數 a = random.randint(0, 9) print('隨機數為:', a) ``` #### 簡易猜數字遊戲 ```python= import random # 讓使用者猜1~5之間的數字,猜中顯示: 猜對了,反之顯示: 猜錯了 # 隨機產生1~5之間的整數 answer = random.randint(1, 5) print('答案:', answer) # 讓使用者猜一個數字 user = int(input('請猜1~5之間的數字: ')) # 比較有沒有猜對 if answer == user: print('猜對了') else: print('猜錯了') ``` #### `list`清單 ```python= # str, int, float, bool # 群集資料型態: list(清單) a = [] # 建立一個空的清單 a = [11, 22, 33, 44, 55, 'abc'] print(type(a)) print(a[4]) a.append(999) # 新增一筆資料到清單 a.remove(33) # 刪除一筆資料 del a[0] print('44' in a) # in用來判斷某一筆資料有沒有在群集內 print('清單資料:', a, ', 資料筆數:', len(a)) ``` #### `in`也可以用來判斷字串 ```python= a = 'Hello this is aaron speaking, today is a good day' if 'today' in a: print('today有出現在文章內') else: print('today沒有出現過') ``` #### 加分 ```python= student_score = [33, 49, 67, 54, 63, 23] new_score = [] # 加分後的成績 for s in student_score: new_score.append(s + 10) print(new_score) ``` #### for comprehension寫法 ```python= student_score = [33, 49, 67, 54, 63, 23] new_score = [s + 10 for s in student_score] print(new_score) ``` ```python= # 請將下面清單內的資料平方後減去1, 並存放到新的清單內顯示出來 a = [5, 6, 8, 2, 4] print([b ** 2 - 1 for b in a]) ``` #### `if`-`else`的簡寫方式 ```python= user = int(input('請輸入一個數字:')) # if user % 2 == 1: # print('奇數') # else: # print('偶數') print('奇數' if user % 2 == 1 else '偶數') ``` #### 資料加總 ```python= # 加總該list內資料並顯示出來 a = [3, 4, 5, 6, 7, 8] sum = 0 # 存放加總用的變數 for b in a: sum += b # sum = sum + b的縮寫方式 print(sum) ``` #### Ubike查詢程式 ```python= import requests import csv url = 'http://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv' response = requests.get(url) if response.status_code == requests.codes.ok: print('取得API資料成功') rows = response.text.splitlines() # 使用csv套件將csv資料轉成list(兩層) data = csv.reader(rows) user_search = input('請輸入要搜尋的站台(部分名稱即可):') # 列出所有站台 for row in data: if user_search in row[3]: print(f'站名: {row[3]}, 地址: {row[6]}') print(f' - 可借: {row[12]}') print(f' - 可還: {row[5]}') else: print('取得Ubike資料失敗') ``` #### 挑戰 ```python= a = [33, 44, 55, 66, 77, 88] print([b for b in a if b % 2 == 1]) ```