# 2024-06-15 中央大學Python基礎班 上課筆記
## 2024-06-29
#### 學生成績管理系統
```python=
# 存放全部成績
# 存放全部成績
grades = {}
def student_system():
load()
while True:
print('=====================================================')
print('= 學生成績股臉系統')
print('=')
print('= 版本: 0.01')
print('= 開發者: Aaron')
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 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('請輸入學號: ')
chinese = input('請輸入國文成績: ')
english = input('請輸入英文成績: ')
math = input('請輸入數學成績: ')
grades[name] = [no, chinese, english, math]
save()
# 測試用
print(grades)
def del_grade():
user_input = input('請輸入學生姓名: ')
if user_input in grades:
del grades[user_input]
else:
print('查無資料')
save()
def save():
with open('student_system.csv', 'w', encoding='utf-8') as file:
for k, v in grades.items():
file.write(f'{k},{v[0]},{v[1]},{v[2]},{v[3]}\n')
def load():
with open('student_system.csv', 'r', encoding='utf-8') as file:
for line in file:
print(line)
line = line.split(',')
grades[line[0]] = [line[1], line[2], line[3], line[4].strip()]
# 測試用
print(grades)
def query_all():
for k, v in grades.items():
print(f'姓名: {k}: 學號: {v[0]}, 國文: {v[1]}, 英文: {v[2]}, 數學: {v[3]}')
def query_by_name():
user_input = input('請輸入姓名: ')
for k, v in grades.items():
if user_input in k:
print(f'姓名: {k}: 學號: {v[0]}, 國文: {v[1]}, 英文: {v[2]}, 數學: {v[3]}')
student_system()
```
#### 不定長度參數2
```python=
def show_me(**argv):
print(argv)
show_me(name='aaron', age=18, phone='0987654321')
```
#### 不定長度參數
```python=
# def plus(a, b):
# return a + b
# def plus(a, b, c):
# return a + b + c
def plus(*argv, ok):
print(argv)
print(ok)
# total = 0
# for i in argv:
# total += i
# return total
# print( plus(1) )
# print( plus(1, 2) )
# print( plus(1, 2, 3, 4, 5) )
plus(1, 2, 3, ok='ok')
```
#### dict
```python=
a = {'a': 99, 77: 88, 'abc': 'Hello', True: 7777, 1: 6666, False: 5555, 0: 4444, (2, 3): 2222}
print(a['a']) # 讀取
print(a['abc'])
a[77] = 88888 # 修改
a[9] = 9 # 新增
del a[77] # 刪除
print(a[(2, 3)])
print(a)
```
#### 模組
my_mod.py
```python=
def my_q(x):
if x % 2 == 0:
return True
else:
return False
a = [12, 37, 55, 98]
if __name__ == '__main__':
print( list(filter(my_q, a)) )
print('我是模組:', __name__)
```
ncu.py
```python=
# import my_mod
# print('模組呼叫:', my_mod.my_q(89))
# print('模組變數:', my_mod.a)
from my_mod import my_q as abc
print(abc(88))
# print(__name__)
import random as r
r.randint(0, 10)
```
#### 過濾偶數
```python=
def my_q(x):
if x % 2 == 0:
return True
else:
return False
a = [12, 37, 55, 98]
print( list(filter(my_q, a)) )
```
#### filter
#### 高階函式
```python=
# 高階函式
def dosomething(f, a, b):
return f(a, b)
result = dosomething((lambda i, j: i + j), 3, 4) # 加法運算
print(result)
result = dosomething((lambda i, j: i * j), 3, 4)
print(result)
a = [23, 65, 87, 45, 99]
# result = []
# for i in a:
# if i < 60:
# result.append(i)
# print(result)
result = list(filter((lambda x: x < 60), a))
print(result)
```
#### 函式指派
```python=
a = (lambda a: a ** 2)(6)
print(a)
def plus(a, b):
return a + b
a = plus # 將plus函式本體指派給a變數, a變數也可以進行呼叫
a = plus(1, 2) # 將plus函式呼叫後將結果存放到a變數,a變數會是一個數字
```
#### 函式名稱其實就是變數
```python=
# def plus(a, b):
# return a + b
# 建立匿名函式
plus = lambda a, b: a + b
print(plus)
print(type(plus))
# a = plus # 把函式指派給a
t = plus(4, 7)
print('你好')
a = print
print = 4
a('哈囉')
```
#### lambda
```python=
# def plus(a, b):
# return a + b
plus = lambda a, b: a + b
t = plus(5, 6)
print(t)
```
#### 指定參數
```python=
# 指定參數
def show_me(name, age, phone, address):
print(f'名字: {name}, 年齡: {age}, 電話: {phone}, 地址: {address}')
show_me('Aaron', 18, '0987654321', '中央大學')
show_me(age=18, address='中央大學', name='Aaron', phone='0987654321')
```
#### 聖誕樹
```python=
# for j in range(1, 6):
# for i in range(j):
# print('*', end='')
# print()
def star(num):
for i in range(num):
print('*', end='')
print()
for i in range(1, 10):
star(i)
```
```python=
print( '\n'.join([''.join(['*' for i in range(j)]) for j in range(1, 6)]) )
```
#### 九九乘法表函示
```python=
# for i in range(2, 9):
# for j in range(1, 9):
# print(f'{i} x {j} = {i * j}')
def nine_nine(a):
for i in range(1, 9):
print(f'{a} x {i} = {a * i}')
for i in range(2, 10):
nine_nine(i)
```
#### 參數預設值
```python=
# 參數預設值
def show_me(name, phone, age='無資料', address='無資料'):
print(f'名字: {name}, 年齡: {age}, 電話: {phone}, 地址: {address}')
show_me('Aaron', 18, '0987654321', '中央大學')
show_me('Aaron', 18, '0987654321')
# show_me('Aaron')
show_me('Aaron', '0987654321')
```
#### 寫一個函式rand3,可以產生3個0~10之間的隨機數,並回傳
```python=
# 寫一個函式rand3,可以產生3個0~10之間的隨機數,並回傳
import random
def rand3():
a1 = random.randint(0, 10)
a2 = random.randint(0, 10)
a3 = random.randint(0, 10)
return a1, a2, a3
r1, r2, r3 = rand3()
print(r1)
print(r2)
print(r3)
```
#### 練習
```python=
def say_hello(name):
print(f'Hello {name}')
say_hello('Aaron')
say_hello('Andy')
def mux(a, b):
return a * b
print( mux(3, 4) )
print( mux(345, 412) )
```
#### return 及格或不及格
```python=
def check(score):
if score < 60:
return '不及格'
else:
return '及格'
r = check(90)
print(r)
r = check(50)
print(r)
```
#### return
```python=
def plus(a, b):
# a = 3
# b = 4
total = a + b
# print(f'總和為: {total}')
return total
# 3 + 4 + 5
r = plus(3, 4)
m = plus(r, 5)
print(f'3 + 4 + 5 = {m}')
```
#### 參數
```python=
def plus(a, b):
# a = 3
# b = 4
total = a + b
print(f'總和為: {total}')
plus(3, 4)
plus(5, 7)
```
#### 函式
```python=
def abc():
print('Hello function')
abc() # 函式呼叫 call function
abc()
```
## 2024-06-22
#### 變數資料交換
```python=
a = 1
b = 2
a, b = b, a
print(a)
```
#### Tuple
```python=
a = (1, 2, 3)
a = (1, 2, 3,)
a = 1, 2, 3
a = 1, 2, 3,
a = 1,
a = 1, 2, 3, 4, 5, # 打包 pack
print(a[3])
print(a[1:3])
print(a)
print(type(a))
# a, b, c, d, e = a # 解包unpack
# print(c)
a1, *a2, a3 = a
print(a1)
print(a2)
print(a3)
```
#### 1A2B
```python=
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) # 另一種把list內資料串接起來的方式
print(f'答案: {answer}')
# 次數
count = 0
while True:
user = input('請猜一個0~9之間不重覆的數字: ')
count += 1
print(f'已經猜了{count}次')
# 檢查輸入的是不是數字
try:
int(user)
except ValueError:
print('只能輸入數字,請重新輸入.')
continue
# if not user.isdigit():
# print('只能輸入數字,請重新輸入.')
# continue
# 檢查是不是四位數
if len(user) != 4:
print('只能輸入四個數字,請重新輸入')
continue
# 檢查數字有沒有重覆
if len(set(user)) != 4:
print('數字不可以重覆,請重新輸入')
continue
if answer == user:
print(f'猜對了,遊戲結束,總共猜了{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')
```
#### 例外
```python=
print('a')
try:
int('88')
[1, 2, 3][3]
except ValueError:
print('轉型失敗')
except IndexError:
print('超過索引值了')
print('a')
print('a')
```
#### 差集、交集、聯集、對稱差集
```python=
employee1 = {'英文', '日語', '粵語', '台語'}
employee2 = {'法語', '德語', '中文', '日語', '台語'}
print(f'只有員工1號會的語言: {employee1 - employee2}')
print(f'只有員工2號會的語言: {employee2 - employee1}')
print(f'兩個人都會的語言: {employee1 & employee2}')
print(f'兩個人全部會那些語言: {employee1 | employee2}')
print(f'只有其中一個人會的語言: {employee1 ^ employee2}')
```
#### 切片
```python=
a = [6, 0, 8, 9, 7, 5, 4, 1, 2, 3]
print(a[2])
print(a[1:4])
print(a[:3])
print(a[2:])
print(a[:])
print(a[-5:-1])
print(a[1:-1])
print(a[-3:])
print(a[:3])
print(a[::2])
print(a[-6:-2:3])
print(a[5:2:-1])
print(a[-2:-9:-2])
print(a[::-len(a)+1])
```
#### 刪除list裡面資料
```python=
a = ['aaron', 'andy', 'apple', 'aaron', 'alan', 'aaron', 'aaron']
while 'aaron' in a:
a.remove('aaron')
print(a)
```
```python=
a = ['aaron', 'andy', 'apple', 'aaron', 'alan']
a.remove('aaron')
print(a)
```
#### while九九乘法表
```python=
for j in range(1, 10):
for i in range(2, 10):
print(f'{i:2} x {j:2} = {i * j:2}', end=' ')
print()
j = 1
while j < 10:
i = 2
while i < 10:
print(f'{i:2} x {j:2} = {i * j:2}', end=' ')
i += 1
print()
j += 1
```
#### 猜數字,猜到對為止
```python=
import random
pc = random.randint(1, 5)
count = 0
while True:
user = int(input('猜1~5之間的數字 => '))
count += 1
if user == pc:
print(f'猜對了, 總共猜了{count}次')
break
else:
print(f'猜錯了, 已經猜了{count}次')
```
#### while
```python=
user = ''
while user != 'quit':
user = input('(quit=離開)=> ')
```
#### for-else
```python=
data = []
for i in range(100000):
user = input('請輸入數字(quit=離開): ')
if user == 'quit':
break
data.append(int(user))
print(data)
# 一般寫法
hasNum = False # 紀錄有沒有偶數
for i in data:
if i % 2 == 0:
hasNum = True
break
if hasNum:
print('有偶數')
else:
print('沒有偶數')
# for-else
for i in data:
if i % 2 == 0:
print('有偶數')
break
else:
print('沒有偶數')
```
#### 另一種九九乘法表
```python=
for j in range(1, 10):
for i in range(2, 10):
print(f'{i:2} x {j:2} = {i * j:2}', end=' ')
print()
```
#### 九九乘法表
```python=
for i in range(2, 10):
for j in range(1, 10):
print(f'{i} x {j} = {i * j}')
print()
```
#### 計算偶數加總
```python=
# break
# continue
a = [23, 45, 6, 2, 97, 4, 8, 77, 6, 27]
total = 0
for i in a:
if i % 2 == 1:
continue
total = total + i
print(f'總合為: {total}')
```
#### 猜拳遊戲
```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('平手')
```
#### match-case
```python=
import random
print('----------------------------------')
print('今日運勢')
print('----------------------------------')
# 0~9隨機產生一個數字
a = random.randint(0, 9)
if a == 0:
print('今天會撿到錢')
elif a == 1:
print('今天會中發票')
elif a == 2:
print('今天會加薪')
elif a == 3:
print('今天會發獎金')
elif a == 4:
print('今天會中彩卷')
else:
print('沒事')
# match-case
match a:
case 0:
print('今天會撿到錢')
case 1:
print('今天會中發票')
case 2:
print('今天會加薪')
case 3:
print('今天會發獎金')
case 4:
print('今天會中彩卷')
case _:
print('沒事')
```
#### 將資料複製到剪貼簿
https://www.delftstack.com/zh-tw/howto/python/python-copy-to-clipboard/
#### 多重分支
```python=
import datetime
t = datetime.date.today()
w = t.weekday() # 0=星期一,5=星期六
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('今天不穿')
```
## 2024-06-15
#### 練習
```python=
for i in range(1, 101):
if i % 2 == 0:
print(i, end=' ')
print()
a = []
for i in range(100000):
user = input('請輸入數字(quit=離開): ')
if user == 'quit':
break
else:
a.append(int(user))
total = 0
for i in a:
total = total + i
print(f'總合為: {total}')
```
#### break
```python=
a = []
for i in range(10000):
user = input('請輸入數字(quit=結束): ')
if user == 'quit':
break
else:
a.append(int(user))
print(a)
```
#### Ubike
#### 資料欄位說明
|索引|欄位名稱|說明|
|-|-|-|
|0|sareaen|行政區英文名|
|1|sarea|行政區中文名|
|2|lng|經度|
|3|sna|中文站名|
|4|snaen|英文站名|
|5|bemp|空位數量|
|6|ar|中文地址|
|7|act|全站禁用狀態(0:禁用、1:啟用)|
|8|sno|站編號|
|9|aren|英文地址|
|10|tot|場站總停車格|
|11|_id|資料編號|
|12|sbi|場站目前車輛數量|
|13|mday|微笑單車各場站來源資料更新時間|
|14|lat|緯度|
> **資料來源:**
>
> https://data.gov.tw/dataset/137993
```python=
import requests
import csv
# 到桃園市Ubike開放平台抓取csv資料
response = requests.get('https://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv&limit=999')
# 將CSV資料的每一行切開存放到list
rows = response.text.splitlines()
# 將每一筆站台資料用逗點切開成小list
rows = list(csv.reader(rows))
print(f'總共: {len(rows)} Ubike站台')
user = input('請輸入站台名稱: ')
isFound = False
for row in rows:
if user in row[3]:
print(f'站名: {row[3]}, 地址: {row[6]}')
print(f' - 可借: {row[12]}')
print(f' - 可還: {row[5]}')
print(f' - 總停車格: {row[10]}')
print()
isFound = True
if not isFound:
print('查無資料')
```
#### a.csv
```
title,name,age,address
ok,aaron,99,XXXXX
hello,andy,88,YYYY
morning,apple,77,ZZZX
```
#### 讀取csv檔案
```python=
import csv
# 打開csv檔案
with open('a.csv') as file:
data = file.readlines()
c = csv.reader(data)
d = list(c)
print(d[2][1])
```
#### range()
```python=
# for i in range(20):
# print(i)
# print( list( range(10) ) )
# print( list( range(5) ) )
for i in range(1, 10):
print(f'2 x {i} = {2 * i}')
```
#### for-in
```python=
a = ['ok', 99, True, [5, 6], 'i']
count = 1
for b in a:
print(b)
print(f'第{count}次')
count = count + 1
```
#### list
```python=
a = [3, 4, 5] # 建立清單 - list
print(type(a))
print(a)
# 新增
a.append(999) # 新增一筆資料
a = a + [999] # 新增一筆資料
print(a)
# 讀取某一筆資料
print(a[2])
print(a[0])
# 修改
a[1] = 'ok'
print(a)
# 刪除資料
a.remove(5) # 以資料內容來刪除
del a[0] # 指定位置來刪除
print(a)
print( len(a) ) # len()函式可以取得list內有幾筆資料
```
#### 猜數字遊戲
```python=
import random # 模組
answer = random.randint(1, 5)
print(f'答案: {answer}')
user = int(input('請猜1~5之間的數字: '))
if answer == user:
print('猜對了')
else:
print('猜錯了')
```
#### in
```python=
# jfadkfsf
# jasdflkjfd
'''
sdfjlskdf
sdfjldkfjs
dsfjsdlfk
'''
a = """
宜蘭美食、美景豐富,還有知名的溫泉資源,是不少北部人週末旅遊、放鬆的好去處。近日就有網友表示,準備和女友去宜蘭玩,但糾結晚上要去羅東還是宜蘭,好奇詢問大家哪邊比較熱鬧?問題抛出後,不少在地人推薦「1地」,更大讚「去過一次終身難忘」。
一名網友在PTT上發文透露, 8月計畫要和女友去宜蘭玩,不過礙於從來沒去過宜蘭,對當地景點非常不了解,只知道第一天要去礁溪,第二天則考慮要住羅東鎮還是宜蘭市,於是好詢問「哪邊比較熱鬧?」
文章一出,網友紛紛回應,「羅東夜市」、「當然是羅東阿」、「羅東是很密集,宜蘭市是很分散,若徒步玩一定是羅東鎮」、「夜市羅東比較多人,商場就新月廣場」、「比吃的羅東也比宜蘭市多」。
但也有另一派在地人大推冬山的清溝夜市,「要逛夜市可以選禮拜三的清溝夜市,很大」、「我建議你去『清溝夜市』會比羅東夜市深刻」、「清溝值得你週3去,走1次終身難忘」、「清溝夜市逛到哭出來 ,一個小時走不完」、「清溝只有週3,最好下午5點前停好車」、「去清溝前先做好功課,什麼該先排先買」。
"""
b = "宜蘭美食、美景豐富,還有知名的溫泉資源,是不少北部人週末旅遊、放鬆的好去處。近日就有網友表示,準備和女友去宜蘭玩,但糾結晚上要去羅東還是宜蘭,好奇詢問大家哪邊比較熱鬧?問題抛出後,不少在地人推薦「1地」,更大讚「去過一次終身難忘」。\
一名網友在PTT上發文透露, 8月計畫要和女友去宜蘭玩,不過礙於從來沒去過宜蘭,對當地景點非常不了解,只知道第一天要去礁溪,第二天則考慮要住羅東鎮還是宜蘭市,於是好詢問「哪邊比較熱鬧?」 \
文章一出,網友紛紛回應,「羅東夜市」、「當然是羅東阿」、「羅東是很密集,宜蘭市是很分散,若徒步玩一定是羅東鎮」、「夜市羅東比較多人,商場就新月廣場」、「比吃的羅東也比宜蘭市多」。 \
但也有另一派在地人大推冬山的清溝夜市,「要逛夜市可以選禮拜三的清溝夜市,很大」、「我建議你去『清溝夜市』會比羅東夜市深刻」、「清溝值得你週3去,走1次終身難忘」、「清溝夜市逛到哭出來 ,一個小時走不完」、「清溝只有週3,最好下午5點前停好車」、「去清溝前先做好功課,什麼該先排先買」。"
print('夜市' in a)
user = input('請輸入關鍵字: ')
if user in a:
print('你輸入的', user, '有在新聞出現.')
print(f'你輸入的 {user} 有在新聞出現')
else:
print('你輸入的', user, '沒有在新聞出現.')
print(f'你輸入的 {user} 沒有在新聞出現.')
```
#### 奇偶數判斷
```python=
a = int(input('請輸入一個數字: '))
if a % 2 == 0:
print('偶數')
else:
print('奇數')
# 單行if
print('偶數') if int(input('請輸入一個數字: ')) % 2 == 0 else print('奇數')
a = 9
if a < 60:
print('不及格')
else:
print('及格')
print('不及格' if a < 60 else '及格')
```
#### if判斷式
```python=
# a = int( input('請輸入一個數字: ') )
# b = int( input('請輸入第二個數字: ') )
# # 算術運算
# print('加法為:', a + b)
# print('減法為:', a - b)
# print('乘法為:', a * b)
# print('除法為:', a / b)
# print('為:', a // b)
# print('為:', a % b)
# print('為:', a ** b)
# 比較運算
# print('3 > 4:', 3 > 4)
# print('5 < 4:', 5 < 4)
# print('9 >= 9:', 9 >= 9)
# print('5 <= 2:', 5 <= 2)
# print('5 == 5:', 5 == 5)
# print('5 != 5:', 5 != 5)
score = int(input('請輸入分數: '))
if score < 60:
print('不及格')
print('Hi')
```
#### 乘法運算
```python=
a = input('請輸入一個數字: ')
print(type(a))
b = int(a) # 把a變數的型態轉型成int型態後存放到b變數
print(type(b))
print('平方後為:', b * b)
```
#### input函式
```python=
a = input('請輸入名字: ')
print('你剛剛輸入的資料是:', a)
```
#### print函式
```python=
# 蟬意
print("Hello 嗨\n你好 Python1", 99 + 1, '123' + '1', 'aaron', end='\n')
print('Hello 嗨你好 Python2')
print( type(99) )
print( type('123') )
print( type(7.8) )
print( type(7.8) )
print( type(True) )
print( type(False) )
# Python保留字
import keyword
print(keyword.kwlist)
# 建立變數a, 並把3存放到變數內
a = 3
hello = 'abc'
print(hello) # 將hello變數內的字串顯示到終端機上
print('hello') # 將hello字串顯示到終端機上
```