# Amkor Python課程2024-04-12 ## 2024-05-10 #### HTML & CSS ```html <!DOCTYPE html> <html> <style> a { color: brown; } .aaron { color:cadetblue; } .andy { text-decoration: none; } #rest { color:yellow; background-color: blue; } .my-image { width: 50%; } </style> <h1>Hi <br /> HTML</h1> <!-- 屬性 --> <a href="https://www.google.com" test="OK" class="">Amkor1</a> <a href="https://www.google.com" test="OK" class="aaron andy">Amkor2</a> <a href="https://www.google.com" id="rest" test="OK" class="aaron">Amkor3</a> <img src="https://www.ana.co.jp/japan-travel-planner/recommendation/itinerary23/img/spot1-1.jpg" class="my-image" /> <article> <h2>子標籤</h2> </article> </html> ``` #### bs4 ```python= import requests from bs4 import BeautifulSoup url = 'https://rate.bot.com.tw/xrt?Lang=zh-TW' response = requests.get(url) # print(response.text) soup = BeautifulSoup(response.text, 'lxml') print(soup.title.text) buttons = soup.find_all('button') for btn in buttons: print(f'按鈕: {btn.text.strip()}, {btn.get("type")}') print(f'{btn.get("class")}') tags = soup.find_all(title='幣別國旗', class_='sp-hong-kong-img') for t in tags: print(t, t.attrs['src']) quiti = {'data-table': '本行現金買入'} tags = soup.find_all(attrs=quiti) for t in tags: print(t) ``` #### 爬取台灣銀行匯率 ```python= import requests from bs4 import BeautifulSoup import time import csv import win32com.client import os url = 'https://rate.bot.com.tw/xrt?Lang=zh-TW' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') tbody = soup.find('tbody') trs = tbody.find_all('tr') result = [] for tr in trs: data = [] # 取得全部的幣別名稱 data.append(tr.td.div.find_all('div')[1].text.strip()) # 取得本行現今買入 quiti = {'data-table': '本行現金買入'} data.append(tr.find_all('td', attrs=quiti)[0].text.strip()) # 取得本行現金賣出 quiti = {'data-table': '本行現金賣出'} data.append(tr.find_all('td', attrs=quiti)[0].text.strip()) # 取得本行即期買入 quiti = {'data-table': '本行即期買入'} data.append(tr.find_all('td', attrs=quiti)[0].text.strip()) # 取得本行即期賣出 quiti = {'data-table': '本行即期賣出'} # 設定要搜尋的屬性值 # 找出tr下的所有td標籤和屬性data-table值為本 tds = tr.find_all('td', attrs=quiti) td = tds[0] # 取出第一個找到的td rate = td.text # 取得第一個td的文字(也就是匯率) rate = rate.strip() # 將多餘的空白和換行去掉 data.append(rate) # 將結果放入list result.append(data) print(result) # 以目前的時間產生檔名 now = time.localtime() file_name = time.strftime('%Y%m%d_%H%M%S.csv') print(f'輸出的檔案: {file_name}') with open(file_name, 'w', encoding='utf-8', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['幣別', '現金買入', '現金賣出', '即期買入', '即期賣出']) writer.writerows(result) # 將csv透過outlook寄出 # 取得outlook元件 outlook = win32com.client.Dispatch("Outlook.Application") # 建立一封新的email mail = outlook.CreateItem(0) mail.To = 'aaronbeango@gmail.com' mail.Subject = '台灣銀行匯率 ' + file_name mail.HTMLBody = '<h1>台灣銀行匯率</h1><br/><h3>' + file_name + '</h3>' full_path = os.path.abspath(file_name) print('完整路徑:', os.path.abspath(file_name)) mail.Attachments.Add(full_path) # 寄出email mail.Send() # 收信 outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") for account in outlook.Accounts: print(account, type(account.DeliveryStore.DisplayName)) mailbox = outlook.Folders(outlook.accounts.Item(1).DeliveryStore.DisplayName) for folder in mailbox.Folders: print(folder) # 指定收件夾 folder = outlook.getDefaultFolder(6) messages = folder.Items.Restrict("@SQL=(urn:schemas:httpmail:subject LIKE '%台灣銀行匯率%')") for message in messages: if hasattr(message, 'Sender'): print(message.Sender) print(message.SenderName) print(message.SenderEmailAddress) print(message.Subject) print(message.ReceivedTime) print(message.Body) if hasattr(message, 'HTMLBody'): print(message.HTMLBody) attachments = message.attachments print('附件數量:', attachments.Count) for attachment in attachments: print(attachment.filename) # 附件的檔名 attachment.SaveAsFile(os.getcwd() + '\\收到-' + attachment.filename) ``` #### `set` ```python= # 1. 沒有索引值,不保證順序 # 2. 資料不會重複 a = {1, 2, 3, 4, 5} a.add(6) a.add(6) a.add(6) a.remove(3) # del不能用 for i in a: print(i) print(a) employee1 = {'英文', '日語', '粵語', '台語'} employee2 = {'法語', '德語', '中文', '日語', '台語'} # 員工1會的語言,但是員工2不會(差集) print(employee1 - employee2) # 兩位員工同時會的語言 - 交集 print(employee1 & employee2) # 兩位員工總共會那些語言 - 聯集 print(employee1 | employee2) # 只有其中一個員工會使用的語言有哪些 - 對稱差集 print(employee1 ^ employee2) ``` #### 模組 ##### a.py ```python= a = 6 def aa(): print('Im aa') if __name__ == '__main__': aa() print(__name__) ``` ##### b.py ```python= #import a from a import aa from a import a aa() aa() print(a) ``` > 1. python程式碼檔案本身就是一個模組 > 2. 透過判斷`__name__`變數可以知道目前的檔案是否是被直接執行或是被當成模組來執行, 如果是直接被執行,則`__name__`的值為`__main__` ## 2024-05-03 #### FTP #### 建立.ssh目錄指令 ``` mkdir C:\\Users\\{你的帳號名稱}\\.ssh ``` ```python= import pysftp host = 'xxx' username = 'xxx' password = 'xxx' cnopts = pysftp.CnOpts() hostkeys = None if cnopts.hostkeys.lookup(host) == None: print("發現新的SFTP站台,將允許該站台憑證 .....") # 將新的憑證存到變數裡 hostkeys = cnopts.hostkeys # 將憑證檢查暫時關閉,避免第一次無法連線, cnopts.hostkeys = None with pysftp.Connection(host, username=username, password=password, cnopts=cnopts) as sftp: # 加入新的憑證 if hostkeys != None: print("連線到該新的SFTP站台並儲存該站台憑證") hostkeys.add(host, sftp.remote_server_key.get_name(), sftp.remote_server_key) hostkeys.save(pysftp.helpers.known_hosts()) # 目前所在路徑 print(sftp.pwd) # 取得目錄詳細內容 directory = sftp.listdir_attr() # 印出結果 for attr in directory: print(attr.filename, attr, sftp.isdir(attr.filename)) # 建立目錄 if not sftp.exists('hello'): sftp.mkdir('hello') # 上傳檔案 # sftp.put('test.mp3', 'c.txt') # 下載檔案 sftp.get('excel_sample_20240503.py', 'excel_sample_20240503.py') # 取得目錄所有內容 print(sftp.listdir()) ``` #### set ![Python-Set-Operatioons](https://hackmd.io/_uploads/HkXWI0WGA.png) #### 建立Excel檔案 ```python= import openpyxl from openpyxl.chart.label import DataLabelList from openpyxl.chart import BarChart, LineChart, Reference data = [ ['', '2017Y', '2018Y', '2019Y', '2020Y', '2021Y', '2022Y', '-', 'Jan\'23', 'Feb\'23', 'Mar\'23', 'Apr\'23', 'May\'23', 'Jun\'23', 'Jul\'23', 'Aug\'23'], ['專案數量' , 13, 27, 40, 65, 67, 29 , '', 3, 0, 5, 7, 2, 4, 6, 2], ['未關閉' , 4, 16, 20, 5, 37, 2 , '', 1, 0, 2, 3, 3, 3, 6, 1], ['關閉或取消', 9, 9, 20, 60, 30, 27 , '', 2, 0, 3, 4, 1, 1, 0, 1], ['暫停' , 3, 2, 4, 6, 6, 2, '', 0, 0, 1, 1, 2, 1, 2, 3], ['關閉率' , 23, 50, 90, 100, 38, 70, '', 30, 40, 50, 66, 95, 85, 67, 80], ['目標' , 80, 80, 80, 80, 80, 80, '', 80, 80, 80, 80, 80, 80, 80, 80], ] wb = openpyxl.Workbook() # 建立工作簿 wb.active.title = '測試' ws = wb.active # 寫入worksheet for row in data: ws.append(row) # 修改cell資料 ws['C2'] = 99 ws.cell(row=3, column=4, value=999) # 取cell資料 print(ws['C2'].value) print(ws.cell(row=3, column=4).value) print(ws['C2'].column) print(ws['C2'].row) print(f'Total column: {ws.max_column}') print(f'Total row: {ws.max_row}') # 取得整份Excel內容 for row in range(1, ws.max_row + 1): for column in range(1, ws.max_column + 1): print(ws.cell(row=row, column=column).value, end=' ') print() for c in ws['C']: print(c.value, end=', ') print() for d in ws['3']: print(d.value, end=', ') print(ws['J:L']) data = ws['J:L'] for row in data: for c in row: print(c.value, end=' ') print() data = ws[1:2] # 取得row 1~2兩個row的資料 for row in data: for c in row: print(c.value, end=' ') print() data = ws['I2':'P7'] for row in data: for c in row: print(c.value, end=' ') print() # wb.save('專案紀錄表.xlsx') # 存檔 wb.close() ``` #### 長條圖 ```python= import openpyxl import openpyxl.chart from openpyxl.chart.label import DataLabelList from openpyxl.chart import BarChart, LineChart, Reference data = [ ['', '2017Y', '2018Y', '2019Y', '2020Y', '2021Y', '2022Y', '-', 'Jan\'23', 'Feb\'23', 'Mar\'23', 'Apr\'23', 'May\'23', 'Jun\'23', 'Jul\'23', 'Aug\'23'], ['專案數量' , 13, 27, 40, 65, 67, 29 , '', 3, 0, 5, 7, 2, 4, 6, 2], ['未關閉' , 4, 16, 20, 5, 37, 2 , '', 1, 0, 2, 3, 3, 3, 6, 1], ['關閉或取消', 9, 9, 20, 60, 30, 27 , '', 2, 0, 3, 4, 1, 1, 0, 1], ['暫停' , 3, 2, 4, 6, 6, 2, '', 0, 0, 1, 1, 2, 1, 2, 3], ['關閉率' , 23, 50, 90, 100, 38, 70, '', 30, 40, 50, 66, 95, 85, 67, 80], ['目標' , 80, 80, 80, 80, 80, 80, '', 80, 80, 80, 80, 80, 80, 80, 80], ] wb = openpyxl.Workbook() # 建立工作簿 wb.active.title = '測試' ws = wb.active # 寫入worksheet for row in data: ws.append(row) data = ws['B6':'P7'] # 將儲存格格式改為百分比 for row in data: for cell in row: if isinstance(cell.value, int): cell.value /= 100 cell.number_format = '0%' # 修改cell資料 # ws['C2'] = 99 # ws.cell(row=3, column=4, value=999) # 取cell資料 print(ws['C2'].value) print(ws.cell(row=3, column=4).value) print(ws['C2'].column) print(ws['C2'].row) print(f'Total column: {ws.max_column}') print(f'Total row: {ws.max_row}') # 取得整份Excel內容 for row in range(1, ws.max_row + 1): for column in range(1, ws.max_column + 1): print(ws.cell(row=row, column=column).value, end=' ') print() for c in ws['C']: print(c.value, end=', ') print() for d in ws['3']: print(d.value, end=', ') print(ws['J:L']) data = ws['J:L'] for row in data: for c in row: print(c.value, end=' ') print() data = ws[1:2] # 取得row 1~2兩個row的資料 for row in data: for c in row: print(c.value, end=' ') print() data = ws['I2':'P7'] for row in data: for c in row: print(c.value, end=' ') print() # 長條圖 bar_chart = BarChart() bar_chart.type = 'col' # 直的=col, 橫的=bar # 建立要產生圖表的資料物件 data = Reference(ws, min_col=1, max_col=16, min_row=2, max_row=5) bar_chart.add_data(data, titles_from_data=True, from_rows=True) xtitle = Reference(ws, min_col=2, max_col=16, min_row=1, max_row=1) bar_chart.set_categories(xtitle) bar_chart.title = '專案紀錄表' bar_chart.x_axis.title = '年度/月份' bar_chart.y_axis.title = '狀態' bar_chart.width = 30 bar_chart.height = 7 bar_chart.gapwidth = 50 # 0-500之間 bar_chart.grouping = 'standard' # stacked, percentStacked bar_chart.dLbls = DataLabelList() bar_chart.dLbls.showVal = True bar_chart.style = 35 # 折線圖 line_chart = LineChart() # 建立要產生圖表的資料物件 data = Reference(ws, min_col=1, max_col=16, min_row=6, max_row=7) line_chart.add_data(data, titles_from_data=True, from_rows=True) # 設定X軸的標籤 line_chart.set_categories(xtitle) # 設定Y軸的資料格式為百分比 line_chart.y_axis.number_format = '0%' # 圖表標題 line_chart.title = '專案達成率' # X軸標題 line_chart.x_axis.title = '年度/月份' # Y軸標題 line_chart.y_axis.title = '狀態' # 圖表大小 line_chart.width = 30 line_chart.height = 7 # 顯示節點上的資料 line_chart.dLbls = DataLabelList() line_chart.dLbls.showVal = True # line_chart.style = 21 # line_chart.y_axis.crosses = 'max' bar_chart.y_axis.axId = 200 bar_chart += line_chart # 將圖表加入工作表 ws.add_chart(bar_chart, 'A10') ws.add_chart(line_chart, 'A23') wb.save('專案紀錄表.xlsx') # 存檔 wb.close() ``` #### openpyxl官方支援的圖表 - Area Charts - [2D Area Charts](https://openpyxl.readthedocs.io/en/stable/charts/area.html#d-area-charts) - [3D Area Charts](https://openpyxl.readthedocs.io/en/stable/charts/area.html#id1) - Bar and Column Charts - [Vertical, Horizontal and Stacked Bar Charts](https://openpyxl.readthedocs.io/en/stable/charts/bar.html#vertical-horizontal-and-stacked-bar-charts) - [3D Bar Charts](https://openpyxl.readthedocs.io/en/stable/charts/bar.html#d-bar-charts) - [Bubble Charts](https://openpyxl.readthedocs.io/en/stable/charts/bubble.html) - Line Charts - [Line Charts](https://openpyxl.readthedocs.io/en/stable/charts/line.html#id1) - [3D Line Charts](https://openpyxl.readthedocs.io/en/stable/charts/line.html#d-line-charts) - [Scatter Charts](https://openpyxl.readthedocs.io/en/stable/charts/scatter.html) - Pie Charts - [Pie Charts](https://openpyxl.readthedocs.io/en/stable/charts/pie.html#id1) - [Projected Pie Charts](https://openpyxl.readthedocs.io/en/stable/charts/pie.html#projected-pie-charts) - [3D Pie Charts](https://openpyxl.readthedocs.io/en/stable/charts/pie.html#d-pie-charts) - [Gradient Pie Charts](https://openpyxl.readthedocs.io/en/stable/charts/pie.html#gradient-pie-charts) - [Doughnut Charts](https://openpyxl.readthedocs.io/en/stable/charts/doughnut.html) - [Radar Charts](https://openpyxl.readthedocs.io/en/stable/charts/radar.html) - [Stock Charts](https://openpyxl.readthedocs.io/en/stable/charts/stock.html) - [Surface charts](https://openpyxl.readthedocs.io/en/stable/charts/surface.html) #### Scheduler ```python= from apscheduler.schedulers.blocking import BlockingScheduler import time from datetime import datetime def job1(): print(f'工作1啟動: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}') def job2(): print(f'工作2啟動: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}') def job3(): print(f'工作3啟動: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}') def job4(): print(f'工作4啟動: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}') # 建立排程器 scheduler = BlockingScheduler(timezone='Asia/Taipei') # 設定排程 scheduler.add_job(job1, 'interval', seconds=5) # 設定排程 scheduler.add_job(job2, 'interval', minutes=1) # 設定排程 scheduler.add_job(job3, 'interval', seconds=1) # 設定排程 scheduler.add_job(job4, 'cron', hour=16, minute=53) # 啟動排程 scheduler.start() print('fksjdflsdjfldjfl') ``` ## 2024-04-26 ## Pandas #### Series ```python= import pandas as pd a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] i = [4, 6, 'aa'] s = pd.Series(a) # 建立Series s1 = pd.Series([1, 2, 3], index=i) print(type(s)) print((s + 1)*2) print(s[ [1, 3, 6] ]) ``` #### dict ```python= # list, tuple, dict字典 a = [1, 2, 3] b = (1, 2, 3) c = {'a':999, True:888, (8, 8): 555} # 無序 # c['b'] = 777 # del c['b'] print(c[True]) print(c[(8, 8)]) ``` #### DataFrame ```python= import pandas as pd # 每個欄位的資料筆數必須相同 data = { 'a': [1, 2, 3, 4], # 'a'=欄位名稱 '姓名': ['aa', 'bb', 'cc', 'dd'], 4: [8, 7, 6, 5] } index = [88, 77, 66, 55] c = [4, 'a', '姓名'] df = pd.DataFrame(data, index=index, columns=c) print(df) print(df.T) df.T.to_excel('test.xlsx') ``` #### select dataframe ```python= import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [32, 47, 63, 21, 98] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) df.to_excel('score.xlsx') print(df) # print(df.loc['B', '姓名']) # print(df.loc['B', ['姓名','國文','數學'] ]) # # 練習: Apple andy的英文成績 # print(df.loc[ ['C', 'D'], '英文' ]) # print(df.loc[ : , ['學號', '姓名'] ]) # print(df.loc[ 'D' , '國文' ]) # Andy的國文成績 # print(df.iloc[3, 2]) print(df.iloc[[1, 2, 4], 1:4 ]) ``` ``` import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [100, 47, 63, 21, 98] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) # df.to_excel('score.xlsx') print(df[ df.英文 < 60 ].loc[:, ['姓名', '英文'] ] ) print(df[ (df.國文 == 100) and (df.數學 == 100) ] ) ``` #### sort ```python= import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [100, 47, 63, 21, 98] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) # df.to_excel('score.xlsx') # df.set_index('數學', inplace=True) # df.sort_index(ascending=True, inplace=True) df2 = df.sort_values(['數學'], ascending=False) print(df2) ``` ``` import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [100, 47, 63, 21, 98] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) # df.to_excel('score.xlsx') # df.英文 = [188, 177, 660, 5, 4] # def doSomething(val): # if val < 60: # return val + 10 # else: # return val # df.英文 = df.英文.apply(doSomething) df.英文 = df.英文.apply(lambda val: val + 100 if val < 60 else 0) print(df) ``` ``` import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [100, 47, 63, 21, 98] } data2 = { '學號': [6, 7], '姓名': ['OK', 'GOOD'], '國文': [71, 61], '英文': [56, 45], '數學': [27, 44] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) df2 = pd.DataFrame(data2) print(df) print(df2) df_result = pd.concat([df, df2], ignore_index=True) print(df_result) ``` ``` import pandas as pd data = { '學號': [1, 2, 3, 4, 5], '姓名': ['Aaron', 'Amber', 'Apple', 'Andy', 'Astrid'], '國文': [100, 90, 80, 70, 60], '英文': [88, 77, 66, 55, 44], '數學': [100, 47, 63, 21, 98] } data2 = { '姓名': ['Amber', 'Apple', 'Astrid'], '歷史': [97, 73, 8], '地理': [ 88, 65, 68] } index = ['A', 'B', 'C', 'D', 'E'] df = pd.DataFrame(data, index=index) index2 = ['B', 'C', 'E'] df2 = pd.DataFrame(data2, index=index2) print(df) print(df2) df_result = pd.merge(df, df2, how='left') print(df_result) df_result.to_excel('test2.xlsx') ``` #### 練習 ```python= import pandas as pd import os def process(part_no): # 讀取Bump Report df_br = pd.read_excel(f'Bump Report_{part_no}.xls') # 讀取plannarity Report df_pr = pd.read_excel(f'planarity Report_{part_no}.xls') # 安裝: pip3 install xlrd lot = df_br.iloc[2, 2] wafarId = df_br.iloc[2, 3] avgHeight = df_br.iloc[4:, 5] avgDiam = df_br.iloc[4:, 9] lms = df_pr.iloc[4:, 10] data = { 'Lot': [lot], 'WafarID': [wafarId], '': [''] } df1 = pd.DataFrame(data) data = { 'Lot': avgHeight, 'WafarID': avgDiam, '': lms } df2 = pd.DataFrame(data) # 合併 df_result = pd.concat([df1, df2]) df_result.to_excel(f'Final_{part_no}.xlsx', index=0) files = os.listdir() for f in files: if 'Bump Report_' in f: part_no = f.replace('Bump Report_', '') part_no = part_no.replace('.xls', '') process(part_no) ``` ## 2024-04-19 #### `elif` ```python= import random # 1~5之間隨機產生一個數字 a = random.randint(1, 5) if a == 1: print('今天會撿到錢') elif a == 2: print('今天會中樂透') elif a == 3: print('今年會加薪') elif a == 4: print('今天股票大漲') elif a == 5: print('沒事') else: 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= # 邏輯運算子 print(not True) print(False and True) a = 2 b = 5 print(a > 3 or b < 9) ``` #### `match-case` ```python= match a: case 1: print('今天會撿到錢') case 2: print('今天會中樂透') case 3: print('今年會加薪') case 4: print('今天股票大漲') case 5: print('沒事') case _: print('程式壞掉了') ``` #### while迴圈 ```python= a = 0 while a < 10: if a % 2 == 0: print(a) a = a + 1 ``` #### `continue` ```python= a = 0 # for-in迴圈 while a < 10: a = a + 1 if a % 2 == 1: continue # 忽略剩下的程式碼, 直接跳到迴圈開頭進行下一次的迴圈 print(a) ``` #### 切片 ```python= a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(a[3:6]) print(a[6:]) print(a[:]) print(a[::2]) print(a[1::3]) # [2, 5, 8] print(a[::-1]) print(a[5::-1]) print(a[-2:-1]) print(a[-3::2]) # 拿[7, 5, 3] print(a[6:1:-2]) # 拿[10, 1] print(a[-1::-len(a)+1]) ``` #### tuple, pack, unpack ```python= # tuple 元組 a = [1, 2, 3, 4, 5] b = (1, 2, 3, 4, 5) print(type(a)) print(type(b)) a[0] = 6 print(b[3:]) a = 1, 2, 3, 4, 5, a1, *a2, a3 = a print(a1) print(a2) print(a3) ``` #### 命名規則 ```python= # define # 1. 名字只能是英文大小寫, 數字, 底線的組合 # 2. 名字第一個字不可以是數字 # 3. 大小寫視為不同的名字 # 4. 不能使用python的關鍵字來命名 a = [22, 33, 66] sum = 0 del sum # 復原功能 print(sum(a)) ``` ```python= def show(): print('hello') print('aaron') show() # 函式呼叫 ``` ``` def show(name): # 小括號內可以透過參數將資料傳遞給函式 print('hello') print(name) show('OK') # 函式呼叫 ``` ```python= def plus(a, b): total = a + b print(f'加總後為: {total}') plus(2, 3) plus(66, 88) ``` #### `resutn` ```python= def plus(a, b): total = a + b # print(f'加總後為: {total}') return total # 將資料回傳給呼叫方 plus(2, 3) result = plus(66, 88) print('result=', result) ``` ```python= # 有參數預設值的參數,右邊的所有參數都必須要有預設值 def showMe(name='無名氏', age='0', phone='無填寫', addr='無填寫'): # 參數預設值 print(f'name={name}') print(f'age={age}') print(f'phone={phone}') print(f'addr={addr}') showMe(99) #### ``` try: # 例外處理 a = int('AA') print(a) except ValueError: print('不是數字') ``` # 指定參數 showMe(age=99, name='aaron', phone='0987654321', addr='.....') a = 3 b = showMe b('一級函式') ``` ```python= import random a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] answer = random.sample(a, 4) # 從a list裡面隨機挑出四筆資料 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('只能輸入4個數字, 請重新輸入') 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 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}次.') ``` ## 2024-04-12 #### h4 ```python= print('Hello Python') hello = 43 print(hello) ``` #### h4 ```python= a = '3' b = '4' print(a + b) ``` #### 四則運算 ```python= print(3 + 1) print(3 - 1) print(3 * 1) print(7 / 2) print(7 // 2) print(7 ** 2) print(7 % 2) ``` #### ```python= user = input('請輸入數字: ') print('你輸入了: ', user) ``` #### 比較運算 ```python= print(3 > 2) a = 99 b = 88 print(a == b) print(b + 11 == a) print(2 ** 1 > 4 // 2) ``` #### 資料型態 ```python= print( type(5) ) print( type('5') ) print( type(True) ) ``` #### h4 ```python= user1 = input('Please input no1: ') user2 = input('Please input no2: ') user1 = int(user1) user2 = int(user2) print(user1 + user2) ``` #### h ```python= # 請寫一個程式,使用者輸入一個數字, # 程式判斷後顯示該數字為奇數或偶數 user = input('請輸入一個數字: ') user = int(user) if user % 2 == 1: print('奇數') else: print('偶數') ``` 簡化的寫法: ```python= # 請寫一個程式,使用者輸入一個數字, # 程式判斷後顯示該數字為奇數或偶數 print('奇數') if int( input('請輸入一個數字: ') ) % 2 == 1 else print('偶數') ``` #### list ```python= a = [33, 44, 55, 66, 77, 88, 99, 1120, 22] print(a) print(a[4]) a.append(4) a.remove(1120) # 用值刪除資料 del a[0] # 用位置刪除資料 print(a, len(a)) ``` #### 二維list ```python= a = [55, 'Aaron', True, [1, 2, 3], ['a', 'b', 'c']] print(a[3][1]) excel = [[1, 2, 3], ['a', 'b', 'c']] print(excel[1][2]) ``` #### ```python= a = [1, 'aaron', True, 'ok', 999] for t in a: print(t) ``` #### h ```python= a = [] # 空list a.append(int(input('請輸入一個數字: '))) a.append(int(input('請輸入一個數字: '))) a.append(int(input('請輸入一個數字: '))) print(a) total = 0 for t in a: total = total + t print('總和:', total) ``` #### while True ```python= a = [] # 空list while True: user = input('請輸入一個數字(quit=離開): ') if user == 'quit': break else: a.append(int(user)) print(a) total = 0 for t in a: total = total + t print('總和:', total) ``` #### in ```python= a = [1, 2, 44, 55, 66] b = 'Today is a good day, my name is aaron' print('55' in a) print('andy' in b) ``` #### \n ```python= print('abcde\n你好') # \n在字串裡是換行的意思 ``` #### 資料欄位說明 |索引|欄位名稱|說明| |-|-|-| |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 #### h4 ```python= import requests import csv # CSV網址 url = 'https://data.tycg.gov.tw/api/v1/rest/datastore/a1b4714b-3b75-4ff8-a8f2-cc377e4eaa0f?format=csv' response = requests.get(url) # 到網頁去抓取資料 rows = response.text.splitlines() data = list(csv.reader(rows)) # 將資料透過csv轉成兩層的list user = input('請輸入要搜尋的場站名稱: ') for row in data: if user in row[3]: print('站名:', row[3], ', 地址:', row[6]) print(' - 可借:', row[12]) print(' - 可還:', row[5]) print() # 這個只是為了多空一行 print(f'站名: {row[3]}, 地址: {row[6]}') print(f' - 可借: {row[12]}') print(f' - 可還: {row[5]}') print() # 這個只是為了多空一行 ```