# 2024-04-27 中央大學Python基礎班 上課筆記
## 2024-05-18
#### 函式
```python=
def say_hello():
print('say')
print('hello')
print('say hello') # 不屬於函式
say_hello() # 呼叫 say_hello函式
say_hello() # 呼叫 say_hello函式
```
#### 加法函式
```python=
def plus():
a = 3
b = 4
print(f'{a} + {b} = {a + b}')
def plus2():
a = 5
b = 7
print(f'{a} + {b} = {a + b}')
def plusV2(a, b): # 參數在函式呼叫的時候,呼叫方必須提供對應數量的參數
print(a)
print(b)
print(f'{a} + {b} = {a + b}')
plus()
plus2()
plusV2(6, 8)
plusV2(16, 18)
plusV2(163, 181)
```
```python=
def mux(a, b, c):
print(f'{a} x {b} x {c} = {a * b * c}')
def test(a):
print(f'{a}的平方為: {a * a}')
mux(2, 3, 4)
test(5)
test(8)
```
```python=
def mux(a, b, c):
# print(f'{a} x {b} x {c} = {a * b * c}')
return a * b * c # 函式內的return關鍵字會讓韓式直接結束
a = mux(2, 3, 4)
b = mux(12, 13, 14)
print(f'a={a}')
print(f'{a + b}')
```
```python=
import random
def rnd():
return random.randint(1, 10)
a = rnd()
print(a)
```
```python=
import random
def rnd():
return random.randint(1, 10)
a = rnd()
print(a)
# 產生三次1~10的隨機數並總和後當成猜數字遊戲的答案
a = rnd() + rnd() + rnd()
print(f'產生三次1~10的隨機數並總和: {a}')
```
#### 參數預設值
```python=
# 有參數預設值的參數,其右邊所有參數都需要提供預設值
def show_me(name, age, address='無', phone='無', birth='無'):
print(f'姓名: {name}')
print(f'年齡: {age}')
print(f'地址: {address}')
print(f'電話: {phone}')
print(f'生日: {birth}')
show_me('Aaron', '99', '0987654321', '00-00-00')
```
#### 指定參數
```python=
# 有參數預設值的參數,其右邊所有參數都需要提供預設值
def show_me(name, age, address='無', phone='無', birth='無'):
print(f'姓名: {name}')
print(f'年齡: {age}')
print(f'地址: {address}')
print(f'電話: {phone}')
print(f'生日: {birth}')
show_me('Aaron', '99', '0987654321', '00-00-00')
show_me(age=99, name='Aaron', phone='0987654321', address='XXXXXXX', birth='00-00-00')
```
#### 打包跟解包
```python=
a = 3
b = 5
a, b = b, a
print(a)
print(b)
```
#### 九九乘法表函式
```python=
def nine_nice(a):
for i in range(1, 10):
print(f'{a} x {i} = {a * i}')
nine_nice(4)
nine_nice(11)
nine_nice(8)
```
#### 聖誕樹
```python=
def tree(a):
for i in range(1, a + 1):
# 輸出每一層的星星
for j in range(1, i + 1):
print('*', end='')
print() # 每一層的換行
tree(4)
```
#### 聖誕樹另一種寫法
```python=
def tree_layer(a):
for i in range(1, a + 1):
print('*', end='')
print()
def tree(a):
for i in range(1, a + 1):
tree_layer(i)
tree(4)
#### 一級函式
```python=
def swap(a, b):
return b, a
a, b = swap(3, 4)
c = swap
aaron = c
a, b = c(5, 6)
aaron = 9
a, b = aaron(7, 8)
print(a, b)
```
```python=
a = [1, 2, 3, 4, 5]
def b(b):
return 999
sum = b
total = sum(a)
print(total)
```
#### lambda
```python=
# def swap(a, b):
# return b, a
# 匿名
a, b = (lambda a, b: (b, a))(5, 6)
# a, b = swap(5, 6)
print(a)
print(b)
```
#### h4
```python=
# a = 80
# # if a < 60:
# # a = a + 10
# # else:
# # a = a
# a = a + 10 if a < 60 else a
# print(a)
a = [1, 2, 3, 4, 5]
# b = []
# for i in a:
# b.append(i + 10)
b = [i + 10 for i in a]
print(b)
```
```python=
a = [33, 44, 55, 66, 77]
a1 = [57, 34, 75, 86, 17]
# def ok(a):
# score = []
# for i in a:
# if i < 60:
# score.append(i + 10)
# else:
# score.append(i)
# return score
newok = lambda a: [i + 10 if i < 60 else i for i in a]
b = newok(a)
print(b)
b = newok(a1)
print(b)
```
####
```ptyhon=
def do_something(a, b, func):
return func(a, b)
result = do_something(6, 7, lambda a, b: a + b)
print(result)
result = do_something(6, 7, lambda a, b: a * b)
print(result)
```
#### mymodule.py
```
def show():
print('This is a module')
if __name__ == '__main__':
print('My module')
show()
print(__name__)
```
#### 20240518.py
```python=
import mymodule
# mymodule.show()
```
#### 字典
```python=
a = { 'ok': 1 , 'a': 2, 99: 'hello'} # dict, 無序
a[99] = 'Hello2' # 修改
a['happy'] = 8888 # 指派資料給不存在的happy這個key, 即為新增資料
print( a['ok'] )
print( a[99] )
del a['a'] # 刪除
print(a, type(a))
# 判斷key是否存在字典
if 99 in a:
print(a[99])
# 判斷值是否存在字典
if 1 in a.values():
print('found')
```
#### 不定長度參數
```python=
def show(a, b, c):
print(a)
print(b)
print(c)
def show2(a, b, c, d):
print(a)
print(b)
print(c)
def show_all1(*args):
print(args)
def show_all2(**args):
print(args)
show_all1(1, 2)
show_all1(1, 2, 4)
show_all1(1, 2, 4, 8)
show_all2(a=1, b=2)
show_all2(aa=1, bb=2, cc=4)
show_all2(hh=1, rr=2, ww=4, nn=8)
```
#### 套件
```python=
import abc123.ok # 呼叫方式: abc123.ok.show_ok()
from abc123 import ok # 呼叫方式: ok.show_ok()
from abc123.ok import show_ok # 呼叫方式: show_ok()
```
#### 讀寫檔案
```python=
with open('python.txt', 'a', encoding='utf-8') as file2:
file.write('Hello Python\n')
a = 4
print(f'寫入檔案 {a}\n', file=file2)
with open('python.txt', 'r', encoding='utf-8', newline='') as file2:
for l in file2.readlines():
print(l, end='')
```
#### 檔案參數
|參數|說明|
|-|-|
|'r'、'r+'|只讀或讀寫,並不建立檔案|
|'w'、'w+'|寫入檔案,若檔案不存在會新建檔案|
|'a'、'a+'|已增加的方式寫入檔案,若檔案不存在會新建檔案。|
|'w'、'w+'|只寫或讀寫,兩者都等同新建一個檔案,故會把原內容清除。|
|'w+'、'r+'的區別|'r+'只能使用在文件存在情況,不存在報Error|
#### 學生成績管理系統
```python=
import csv
grades = {} # 存放全部資料的字典
def student_system():
# 載入資料
load()
while True:
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':
break
else:
print('輸入錯誤,請重新輸入!')
def management():
while True:
print('============================================')
print('管理學生成績')
print('============================================')
print('1. 新增資料')
print('2. 刪除資料')
print('3. 回主選單')
user_input2 = input('=> ')
if user_input2 == '1':
add_grade()
elif user_input2 == '2':
del_grade()
elif user_input2 == '3':
break
else:
print('輸入錯誤,請重新輸入!')
def del_grade():
name = input('請輸入要刪除資料的姓名: ')
if name in grades:
del grades[name]
print(f'{name} 已刪除')
else:
print(f'查無此人')
save()
# 新增成績
def add_grade():
name = input('輸入姓名: ')
no = input('輸入學號: ')
chinese = input('輸入國文成績: ')
english = input('輸入英文成績: ')
math = input('輸入數學成績: ')
grades[name] = [no, chinese, english, math]
save()
# 測試用
print(grades)
def save():
with open('student_system.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile) # 建立csv writer
# 寫入標題
writer.writerow(['姓名', '學號', '國文', '英文', '數學'])
for key in grades:
# 將字典的一筆資料攤平成list
a = [key, grades[key][0], grades[key][1], grades[key][2], grades[key][3]]
writer.writerow(a)
def load():
with open('student_system.csv', 'r', encoding='utf-8', newline='') as csvfile:
reader = csv.reader(csvfile)
# 跳過csv標題
next(reader)
for row in reader:
grades[row[0]] = [row[1], row[2], row[3], row[4]]
print(grades)
def query():
while True:
print('============================================')
print('查詢學生成績')
print('============================================')
print('1. 查詢全部資料')
print('2. 依姓名查詢資料')
print('3. 回主選單')
user_input2 = input('=> ')
if user_input2 == '1':
query_all()
elif user_input2 == '2':
query_by_name()
elif user_input2 == '3':
break
else:
print('輸入錯誤,請重新輸入!')
def query_all():
for key in grades:
print(f'姓名: {key}({grades[key][0]}): 國文={grades[key][1]}, 英文={grades[key][2]}, 數學={grades[key][3]}')
def query_by_name():
name = input('請輸入姓名: ')
for key in grades:
if name in key:
print(f'姓名: {key}({grades[key][0]}): 國文={grades[key][1]}, 英文={grades[key][2]}, 數學={grades[key][3]}')
student_system()
```
## 2024-05-11
#### 數字加總
```python=
a1 = int( input('請輸入第1個數字:') )
a2 = int( input('請輸入第2個數字:') )
a3 = int( input('請輸入第3個數字:') )
total = a1 + a2 + a3
print( type(total) )
print('加總後為: ' + str( total ) )
```
#### 查保留字
```python=
import keyword
print(keyword.kwlist)
```
#### range()
```python=
a1 = list(range(3))
a2 = list(range(2, 8))
a3 = list(range(5, 10, 2))
print(a1)
print(a2)
print(a3)
print(list(range(-1, -4, -1)))
print(list(range(8, 5, -1)))
```
#### 用迴圈輸入3個整數
```python=
total = 0
for a in range(3):
user = int( input('請輸入第' + str(a + 1) + '個數字: ') )
total += user
print('加總後為: ' + str(total))
```
#### 輸入任意個整數後加總
```python=
total = 0
for a in range(10000):
user = input('請輸入第' + str(a + 1) + '個數字(輸入quit=離開): ')
if user == 'quit':
break # 跳離迴圈
else:
total += int(user)
print('加總後為: ' + str(total))
```
#### 只加總偶數
```python=
total = 0
for a in range(10000):
user = input('請輸入第' + str(a + 1) + '個數字(輸入quit=離開): ')
# 判斷是不是輸入quit
if user == 'quit':
break # 跳離迴圈
user = int(user)
# 判斷如果是奇數就不做加總
if user % 2 == 1:
continue
total += int(user)
print('加總後為: ' + str(total))
```
#### 另一種寫法
```python=
total = 0
all_num = []
for a in range(10000):
user = input('請輸入第' + str(a + 1) + '個數字(輸入quit=離開): ')
# 判斷是不是輸入quit
if user == 'quit':
break # 跳離迴圈
else:
user = int(user)
if user % 2 == 0:
all_num.append(user)
print('加總後為: ' + str(sum(all_num)))
```
#### while
```python=
a = 0
while a < 3:
print(a)
a += 1
```
```python=
a = 3
while a < 8:
print(a)
a += 2
```
```python=
a = 1
while True:
print(a)
a += 1
```
####
```python=
total = 0
count = 1
while True:
user = input(f'請輸入第{count}個數字(輸入quit=離開): ')
if user == 'quit':
break # 跳離迴圈
else:
total += int(user)
count += 1
print(f'加總後為: {total}')
```
#### `elif`
```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('星期六: 今天適合穿白色')
else:
print('星期日: 今天適合穿彩色')
```
#### 抽籤
```python=
import random
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`
```python=
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('平手')
```
#### 切片
```python=
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[2::2])
print(a[-6:8:3])
print(a[-1:-6:-1])
print(a[8::-1])
print(a[3:-1:3])
print(a[::-3])
print(a[-2:-8:-2])
print(a[4:7:-1])
```
#### 例外捕捉
```python=
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
try:
print(a[10])
except IndexError:
print('Oh~No~')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
```
#### 練習
幫忙加上例外捕捉:
```python=
while True:
user = input('請輸入一個數字: ')
user = int(user)
print(f'你輸入的數字是: {user}')
```
參考答案:
```python=
while True:
user = input('請輸入一個數字: ')
try:
user = int(user)
print(f'你輸入的數字是: {user}')
except ValueError:
print(f'你輸入的不是數字,請重新輸入')
```
#### set
```python=
a = {1, 2, 3}
a.add(6)
a.add(2)
a.add(2)
a.add(2)
a.add(2)
print(f'set: {a} 有{len(a)}筆資料')
for i in a:
print(i)
```
#### 差集, 交集, 聯集, 對稱差集
```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}')
```
#### `tuple`
```python=
# tuple 元組
# set集合
# list清單(array陣列)
# 跟list一樣, 唯一差別tuple是唯讀的,一經建立,內容就不改變
# pack跟unpack
a = (1, 2, 3,)
a = 1, 2, 3
a = 1, 2, 3,
a = 3,
a = 5, 6, 7, 8, 9
print(a, type(a))
a1, a2, a3, a4, a5 = a
print(a1, type(a1))
print(a2, type(a2))
print(a3, type(a3))
print(a4, type(a4))
print(a5, type(a5))
a1, a2, *a3 = a
print(a1, type(a1))
print(a2, type(a2))
print(a3, type(a3))
```
#### 猜數字遊戲
```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)
print(f'答案: {answer}')
guess_count = 0 # 紀錄猜測的次數
while True:
user = input('請猜0~9之間的四位數字(不可重覆): ')
guess_count += 1 # 次數加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_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')
```
## 2024-04-27
#### basic
```python=
print('Hello Python') # 字串string
print('今天天氣很好')
a = 3 # assign 指派
print(a) # 變數
b = "你好"
print(b)
a = 3
a = 9
b = '3'
print(1 + 1)
print(a + 1)
print(b + '1')
```
```python=
print('123', '456', '你好')
print(3+4)
print(6-2)
print(6*2)
print(6/2)
print(7 / 2)
print(6 ** 2)
print(7 // 2)
print(7 % 2)
print(999 % 2)
a = 98
b = 2
print(a * b)
```
#### input函式與轉型
```python=
a = input('請隨意輸入:')
b = int(a)
print('a型態: ', type(a))
print('b型態: ', type(b))
print('你輸入的是:', a * 2)
print('你輸入的是:', b * 2)
```
#### if
```python=
if False: # 裡面的程式碼
print('a1')
print('a2')
print('a3')
```
```python=
# 比較運算子,運算結果為True或是False
print( 3 > 4 )
print( 8 >= 4 )
print( 5 == 5 )
print( 5 != 5 )
a = 9
b = 8
print(a <= b)
```
```python=
score = input('請輸入分數:')
score = int(score) # 轉型
if score < 60:
print('不及格')
else:
print('及格')
```
#### 判斷奇偶數
```python=
user = input('請輸入一個數字:')
user = int(user)
result = user % 2 # 除以2之後取餘數
if result == 0:
print('偶數')
else:
print('奇數')
```
##### 單行寫法
```python=
print('偶數' if int( input('請輸入一個數字:') ) % 2 == 0 else '奇數')
```
#### f-string
```python=
s = '李李仁跟陶晶瑩4月送女兒荳荳赴美國念書, 女兒5月底即將畢業,正考慮要在新加坡還是美國繼續升大學,兒子小龍今年1月已赴新加坡念書,陶子透露學費表示:「非常合理也便宜,在美國念1年大學的錢可以在新加坡念6年。」陶晶瑩兒女都留學(圖/記者楊澍攝)陶晶瑩兒女都留學(圖/記者楊澍攝)陶晶瑩透露她今飛回台灣,有網友說今天雨下太大了,導致天空塞機,陶晶瑩則說她降落的時候雨還沒下,進一步透露:「我朋友剛剛在桃機落地、根本沒有下雨!但是他們已經等半個小時沒有停機坪⋯⋯⋯」。更多三立新聞網報導50歲謝金燕痛哭!自封「閩南語歌手」 投奔中國《浪姐5》爆內幕《全明星》女神見習婚禮 相識多年男伴首曝光!鬆口想凍卵生子鄭靚歆同志婚落淚 「謝謝妳給我滿滿高潮」!生父卻意外缺席鄭靚歆女女戀婚禮 美魔女媽媽胡文英辣翻了!「網狀透視裝」震撼登場'
user = input('請輸文字:')
if user in s:
print('您輸入的字:', user, '有在新聞出現過')
print(f'您輸入的字: {user} 有在新聞出現過')
else:
print('您輸入的字:', user, '沒有在新聞出現過')
print(f'您輸入的字: {user} 沒有在新聞出現過')
```
#### list
```python=
a = [1, 2, 3, 4, 5]
print(type(a))
print(a)
print(a[2])
print(a[5])
```
```python=
a = [0, 2, 3, 'aa', 'q', True, [1, 2, 3]]
a[4] = 'Q'
print( len(a) )
print( a[6][1] )
print(a)
```
#### list的CRUD
```python=
a = [0, 2, 3, 'aa', 'q', True, [1, 2, 3], 'aa', 'aa']
a[4] = 'Q'
a[6][0] = '99'
print( len(a) )
print( a[6][1] )
if 'aa2' in a:
a.remove('aa2') # 刪除aa
del a[0]
a.append(999)
a.insert(0, 888)
print(a)
a[6].insert(2, 'OK')
print(a)
```
> **備註:**
> list裡面的子list也可以被remove方法移除
#### 指派運算子
```python=
a = 3
a = a + 2
a += 2
a **= 3
a %= 2 # 這是註解
# +=, -=. *=, /=, **=, //=, %=
print(a)
```
#### 計算加總
```python=
a = [11, 32, 43, 65, 77]
total = 0
for t in a:
print(t)
total = total + t
print(total)
```
####
```python=
a = ['Aaron', 'Andy', 'Apple', 'Amber', 'Astrid']
#-----------------------------------------------
# Hello, Aaron
# Hello, Andy
# Hello, Apple
# Hello, Amber
# Hello, Astrid
for name in a:
print(f'Hello, {name}')
```
#### 桃園ubike
```python=
import requests
import csv
url = 'http://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv'
resp = requests.get(url) # 去該網址爬資料下來
print(resp.text)
rows = resp.text.splitlines()
# 透過csv套件, 將資料傳成兩層list
data = list( csv.reader(rows) )
user = input('請數入站名: ')
for row in data:
if user in row[3]:
print(f'站名: {row[3]}, 地址: {row[6]}')
print(f' - 可借: {row[12]}')
print(f' - 可還: {row[5]}')
print()
```