Try   HackMD

2023-12-02 Python入門實作班 上課記錄

目錄

2023-12-02
2023-12-09
2023-12-16

2023-12-16

函式

import keyword print(keyword.kwlist) def show(): print('Hello', end='') print(' function') show() show() show() show() show() show() show() show() show() show()

函式參數

def plus(a, b): print(f'a = {a}') print(f'b = {b}') print(f'總合為: {a + b}') plus(1, 2) plus(99, 77) plus('aa', 77)
def plus(a, b): try: int(a) int(b) print(f'a = {a}') print(f'b = {b}') print(f'總合為: {a + b}') except ValueError: print('輸入了錯誤型態的資料') plus(1, 2) plus(99, 77) plus('aa', 77)
def plus(a, b): if type(a) is int: print(f'a = {a}') print(f'b = {b}') print(f'總合為: {a + b}') else: print('參數必須為int型態') plus(1, 2) plus(99, 77) plus('22', 77)
def plus(a, b): if isinstance(a, int): print(f'a = {a}') print(f'b = {b}') print(f'總合為: {a + b}') else: print('參數必須為int型態') plus(1, 2) plus(99, 77) plus('22', 77)
def plus(a, b): if isinstance(a, (int, float)): print(f'a = {a}') print(f'b = {b}') print(f'總合為: {a + b}') else: print('參數必須為int型態') plus(1, 2) plus(99, 77) plus(2.2, 77)
def say_hello(name): print(f'Hello, {name}') say_hello('Aaron') say_hello('Apple') say_hello('Andy')
def check(num): if num % 2 == 0: print('偶數') else: print('奇數') check(321) check(999) check(1322)
def plus(a, b): # print(f'{a + b}') return a + b a = plus(1, 2) b = plus(3, 4) print(a)

產生連續數字

def gen_num(num): print( ' '.join( [str(n) for n in list(range(1, num + 1))] ) ) gen_num(9) gen_num(5)

變數交換

a = 3 b = 4 def swap(a, b): return b, a a, b = swap(a, b) print(a) print(b)

階乘函式

def factorial(num): result = 1 for n in range(2, num + 1): result *= n return result print(factorial(4)) print(factorial(6)) print(factorial(10)) print(factorial(100))

參數預設值

# 參數預設值 # 有預設值的參數右邊全部參數都需要有預設值 def show_me(name, age = '無資料', phone = '無資料', address = '無資料'): print(f'姓名: {name}') print(f'年齡: {age}') print(f'電話: {phone}') print(f'地址: {address}') show_me('aaron', 99, '0987654321')

指定參數

def show_me(name, age = '無資料', phone = '無資料', address = '無資料'): print(f'姓名: {name}') print(f'年齡: {age}') print(f'電話: {phone}') print(f'地址: {address}') show_me(phone='我的電話', name='aaron') print('aaa', end='')

一級函式

def plus(a, b): return a + b c = plus print( c(6, 7) )

callable

def plus(a, b): return a + b c = plus # print( c(6, 7) ) if callable(c): # 可以被呼叫 print(c(1, 3)) else: print('c不是函式')

lambda函式呼叫

print( (lambda num: '偶數' if num % 2 == 0 else '奇數')(999) )

dict

a = {3: 99, 'name': 'aaron', True: 88} a['name'] = 'andy' # 修改資料 a['abc'] = 777 # 新增一筆資料 del a['name'] print(a[3]) if a['name'] in a: print(a['name']) print(a[True]) print(a)
a = {3: 99, 'name': 'aaron', True: 88} a['name'] = 'andy' # 修改資料 a['abc'] = 777 # 新增一筆資料 del a['name'] print(a[3]) if 'name' in a: print(a['name']) print(a[True]) print(a) for n in a: print(f'key={n}, value={a[n]}') print(list(a.keys())) print(list(a.values()))

不定長度參數

def count_all(*args): total = 0 print(type(args)) for a in args: total += a return total print(count_all()) print(count_all(1, 2, 3)) print(count_all(1, 2, 3, 4, 5)) print(count_all(1, 2, 3, 4, 5, 6, 7))
num_filter = lambda *args: [n for n in args if n % 2 == 0] print(num_filter(1, 2, 3, 4, 5)) print(num_filter(1, 2, 3, 4, 5, 6, 7)) print(num_filter(1, 2, 3, 4, 5, 6, 7, 8, 9, 0))
a = {3: 88, 'name': 987, 'ok': 'hello'} print(3 in a) print(987 in a.values())

模組

hello.py
def func1(): print('方法一號') def func2(a, b): print(f'方法二號: {a}, {b}') username = 'aaron' if __name__ == '__main__': func1() func2(1, 2) print(__name__)
callmodule.py
import hello hello.func2(99, 88) hello.func1() hello.func1() print(hello.username)

另一種模組import方式

# import hello # hello.func2(99, 88) # hello.func1() # hello.func1() # print(hello.username) from hello import func1 from hello import func2 from hello import username func1() func2(44, 55) print(username)

學生成績管理系統

# 學生成績管理系統 # 主功能: # 1. 管理學生成績 # - 新增學生成績 # - 刪除學生成績 # 2. 查詢學生成績 # - 依姓名查詢 # - 查詢全部 # # (資料存檔,資料讀取,CSV格式) import csv # 學生所有資料 grades = {} # 主程式 def student_system(): load() 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('Bye~') 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() pass elif user_input == '3': break else: print('無效的輸入') 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() elif user_input == '3': break else: print('無效的輸入') def add_grade(): name = input('請輸入學生姓名: ') no = input('請輸入學號: ') mandrin = input('請輸入國文成績: ') englith = input('請輸入英文成績: ') math = input('請輸入數學成績: ') # 新增一筆資料到字典 grades[name] = [no, mandrin, englith, math] # 存檔 save() print('新增完成') print(grades) # 測試用,確認資料 def del_grade(): name = input('請輸入學生姓名: ') if name in grades: del grades[name] save() print('刪除成功') 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 query_by_name(): user_input = input('請輸入學生姓名(部分即可): ') for name in grades: if user_input in name: print(f'姓名: {name}, 學號: {grades[name][0]}, 國文: {grades[name][1]}, 英文: {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]) writer.writerow(data) # 讀檔 def load(): with open('student_system.csv', 'r', encoding='utf-8') as file: reader = csv.reader(file) # 跳過第一筆資料 next(reader) for row in reader: # ['aaron', '1234', '98', '88', '76] grades[row[0]] = row[1:] print(grades) student_system()

2023-12-09

ifelifelse

今日運勢:

import random # 0 = 今天會撿到錢 # 1 = 今天會加薪 # 2 = 今天中統一發票 # 3 = 今天沒事發生 # 4 = 今天有人請你吃飯 result = random.randint(0, 4) if result == 0: print('今天會撿到錢') elif result == 1: print('今天會加薪') elif result == 2: print('今天中統一發票') elif result == 3: print('今天沒事發生') else: print('今天有人請你吃飯')

今日穿搭建議

import datetime weekday = datetime.date.today().weekday() if weekday == 0: # 星期一 print('星期一: 今天適合穿藍色') elif weekday == 1: # 星期二 print('星期二: 今天適合穿紅色') elif weekday == 2: # 星期三 print('星期三: 今天適合穿黃色') elif weekday == 3: # 星期四 print('星期四: 今天適合穿綠色') elif weekday == 4: # 星期五 print('星期五: 今天適合穿紫色') elif weekday == 5: # 星期六 print('星期六: 今天適合穿彩色') else: # 星期日 print('星期日: 今天適合穿黑色')

猜拳遊戲

import random pc = random.randint(0, 2) # 0 = 剪刀, 1 = 石頭, 2 = 布 game = ['剪刀', '石頭', '布'] print(f'電腦出: {game[pc]}') user = int(input('請出拳(0 = 剪刀, 1 = 石頭, 2 = 布): ')) print(f'你出了: {game[user]}') 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('平手')

函式注意事項

a = [11, 22, 33] sum2 = 4 + 5 del sum # 刪除掉變數 result = sum(a) print(result)

索引切片

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(a[-2:-7:-2]) print(a[::len(a)-1]) print(a[1::3])

range

a = range(9, 5, -1) print(list(a)) a = range(-1, -4, -1) print(list(a))

結果:

[9, 8, 7, 6] [-1, -2, -3]

2的九九乘法表

for i in range(1, 10): print(f'2 x {i} = {i*2}')

可以猜三次的猜數字遊戲

import random # 隨機0~5之間的整數 answer = random.randint(0, 5) for i in range(1, 4): user = int( input('請猜一個數字(0~5): ') ) if user == answer: print(f'猜對了, 你總共猜了{i}次') break else: print(f'猜錯了, 剩下{3-i}次')

for comprehension

一般寫法:

a = [33, 42, 57, 80, 17, 66] b = [] for score in a: if score < 60: b.append(score + 10) print(b)

for comperhension寫法:

a = [33, 42, 57, 80, 17, 66] print([score + 10 for score in a])

單行if

import random pc = random.randint(0, 2) print(pc) user = int(input('猜一個數字(0~2): ')) print('猜對了' if pc == user else '猜錯了') # if pc == user: # print('猜對了') # else: # print('猜錯了')

for comprehension + 單行

a = [33, 42, 57, 80, 17, 66] print([score + 10 for score in a]) # 全部加10分 print([score + 10 if score < 60 else score for score in a]) # 只有不及格的加10分 print([score + 10 for score in a if score < 60]) # 只有不及格的加10分, 且只保留不及格的分數

set

a = {1, 2, 3, 4} # set a.add(5) a.add('aaron') a.add('aaron') a.add(3) a.add(2) a.remove(5) a.remove('aaron') # del a[9] for i in a: print(i)
a = {1, 2, 5, 7, 9} b = {3, 4, 9, 10, 12} print(a - b) # 差集 print(a & b) # 交集 print(a | b) # 聯集 print(a ^ b) # 對稱差集

打包與解包

a = (1, 2, 3,) print(a) a = (1, 2, 3) print(a) a = 1, 2, 3, print(a) a = 1, 2, 3 print(a) a = (5,) print(a) a = (5) print(a) a = 5, print(a) a = 5 print(a) a = (1, 'a', 44, 99, 'hello') a, b, c, d, e = a # 解包 unpack print(a) print(b) print(c) print(d) print(e) a = a, b, c, d, e # 打包(pack) print(a) a, *b, c = a print(a) print(b) print(c) a = (1, 'a', 44, 99, 'hello') a, b, *c = a print(a) print(b) print(c) a = (1, 'a', 44, 99, 'hello') *b, c = a print(b) print(c)

完整九九乘法表

for outer in range(2, 10): for inner in range(1, 10): print(f'{outer} x {inner} = {outer * inner}')

畫星星

for i in range(1, 6): for j in range(1, i + 1): print('*', end='') print() for i in range(1, 6): print('*' * i)

例外捕捉

import random pc = random.randint(0, 3) a= [] try: print(a[1]) except IndexError: print('存取list失敗') for times in range(1, 4): try: user = int(input('請猜一個數字(0~3): ')) except ValueError: print(f'輸入錯誤, 還剩{3-times}次') continue # 取消剩下的程式碼執行,直接進入迴圈的下一次 if pc == user: print(f'猜對了,總共猜了{times}次') else: print(f'猜錯了,還剩{3-times}次')

while迴圈

user = [] while True: user_input = input('請輸入數字(quit=停止輸入): ') if user_input == 'quit': break else: try: user.append(int(user_input)) except ValueError: print('輸入錯誤,請重新輸入!') print(f'總和: {sum(user)}')

猜數字遊戲

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 # 次數加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 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-12-02

輸出

print('Hello Python')
print('Hello', 'Python', end='') print('今天天氣很好')

輸入

print('Hello Python') print('第二行程式碼') a = input() print('你剛剛輸入了:', a)

註解

print('Hello Python') a = input('請輸入姓名:') b = input('請輸入年齡:') c = input('請輸入性別:') # 這是註解 print('你的名字:', a, ', 年齡:', b, ', 性別:', c) # 這是註解

Ctrl + / 可以將選取的程式碼變成註解

字串格式化: f-string(f字串)

print('1', '2', '3', sep='') print('Hello Python 今天 天氣', end='') print('第二行程式碼') a = input('請輸入姓名:') b = input('請輸入年齡:') c = input('請輸入性別:') print('你剛剛輸入了:', a, b, c) # dajflkjdlfkjaldfjaldfj # fjaldkjflkajdfldafj # fjdalsfjladjflajdfkljadf # fajldkfjalkdfjldfjlad # ajdflkajdfladjfldskf print('你的名字: ', a, ', 年齡: ', b, ', 性別: ', c, sep='') # 這是筆記(註解) print(f'你的名字: {a}, 年齡: {b}, 性別: {c}' )

練習

請解決加總後輸出結果不正確問題:

print('1' + '1') print( int('1') + 1) # int('1') 將字串1轉型成數字1 print(1 + 1) print(5 * 2) print('Hello' * 6) print( type('4') ) # 輸出字串4的型態 print( type(4) ) # 輸出4的型態 a1 = input('請輸入第一個數字:') a2 = input('請輸入第2個數字:') print(f'總合為: {a1 + a2}')

答案:

print('1' + '1') print( int('1') + 1) # int('1') 將字串1轉型成數字1 print(1 + 1) print(5 * 2) print('Hello' * 6) print( type('4') ) # 輸出字串4的型態 print( type(4) ) # 輸出4的型態 a1 = int( input('請輸入第一個數字:') ) # input()輸入的資料永遠都字串型態 a2 = int( input('請輸入第2個數字:') ) a1 = int(a1) a2 = int(a2) print(f'總合為: {int(a1) + int(a2)}')

有三種方式

print( 35 % 2 ) print( 5 ** 2 ) print( 100 // 9 )

超陽春猜數字遊戲

import random a = random.randint(4, 9) # 產生0~5之間的隨機數 print(a) user = int( input('請猜一個數字: ') ) if a == user: print('猜對了') # 條件成立會執行這裡 else: print('猜錯了') # 條件不成立會執行這裡
user = input('請輸入一個數字:') user = int(user) if user % 2 == 1: print('奇數') else: print('偶數')

Python套件

import requests # 爬取網頁資料 a = requests.get('http://www.aaronlife.com/v1/teaching/_timetable_ncu_python_2023-12-02.html') # 設定網頁編碼 a.encoding = 'utf-8' print(a.text)

list

a = [] # 建立一個空的list a.append(3) # append將資料加到list內 a.append(4) a.append(5) a.append(6) a.append(7) a[1] = 'Hi' # a.remove(6) del a[3] print(a) print(a[2]) print(99 in a) # print('健行' in '健行科技大學')

幫list內的每筆資料加上40

a = [33, 45, 42, 65, 23] result = [] for t in a: result.append(t + 40) print(result)

list資料加總

a = [11, 22, 33, 44, 55, 66, 77] total = 0 for t in a: total += t # total = total + t print(f'total現在是: {total}')

UBike

OpenData API網址: 'http://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv'

import requests import csv response = requests.get('http://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv') print(response.status_code) if response.status_code != 200: print('取得ubike資料失敗') else: print('取得ubike資料成功') rows = response.text.splitlines() # 將每一列資料轉成list rows = csv.reader(rows) user = input('請輸入站台的部份名稱: ') for row in rows: if user in row[3]: print(f'站台名稱: {row[3]}') print(f' - 總數量: {row[10]}') print(f' - 可借: {row[12]}') print(f' - 可還: {row[10]}') print()