# Python Entry-level ###### tags: `CS` `Python` ### Python筆記 **在python程式縮排很重要** **python思考比較人性化** 在mac環境上使用vsc做編輯器,需在原始碼檔案中新增編碼宣告 ```python= # coding=utf8 ``` #### 關於Terminal操作 python 檔名.py(如要用python3 要打python3 檔名.py) 可以用方向鍵 clear清空terminal ## 資料型態 可變列表list[](有順序 可變動的資料集合) 固定列表tuple()(有順序 不可變動的資料) 集合{}(無順序性的資料集合) 字典{"":""}(鍵值對(key-value pair)的集合) 變數(可用來存放資料的自訂名稱) ## 資料型態の基本運算 ### 數字運算 x的y次方(x**y)p.s可以用0.5拿來開根號 小數除法(x/y) 可以除到小數 整數除法(x//y)只取整數,小數不看 取餘數(x%y) ### 字串運算 \為逸出字元 ```python= #跳脫 (\")可以在字串中顯示 s = "Hello\"o" print(s) #結果:Hello"o #字串串接(+也可以用空白鍵取代) s ="hello"+"world" print(s) #結果:Helloworld #使用"""code""" 可以直接換行 s ="""hello world""" print(s) #結果:Hello # world #字元乘法 s ="hello"*3+"world" print(s) #結果:hellohellohelloworld #字串會對內部的字元編號,從0算起 s= "hello" print(s[0]) #結果:h #也可以這樣使用 print(s[1:4])#不包含4 #結果:ell #還可以這樣使用,不給結尾 print(s[1:]) #結果:ello ``` ### 有序列表運算 #### List運算 ```python= #索引查詢 grades = [12,60,15,70,90] print(grades[0]) #結果:12 grades[0] = 20 #直接修改 print(grades) #結果:[20,60,15,70,90] print(grades[1:4])#不包含4 #結果:[60,15,70] grades[1:4]=[]#連續刪除列表中的索引,包含4 print(grades) #結果:[20,90] #列表也可以串接 grades = grades+[12,33] print(grades) #結果:[20,90,12,33] #取得列表長度 length=len(grades) print(length) #結果:4 ``` ##### 巢狀列表 ```python= data = [[3,4,5],[6,7,8]] print(data[0][1]) #結果:4 data[0][0:2] = [5,5,5]#把3,4換成5,5,5 print(data) #結果:[[5,5,5,5],[6,7,8]] ``` #### Tuple運算 ```python= data = (3,4,5) print(data[0:2]) #結果:(3,4) #與list只差在資料無法更動 ``` ### 集合與字典運算 #### set運算 ```python= #判斷有無 s1 = {3,4,5} print(3 in s1) print(10 in s1) #結果:True #false print(10 not in s1) #結果:True s2 = {4,5,6,7} s3 = s1&s2 #取交集 print(s3) #結果:{4,5} s3 = s1|s2 #取聯集 print(s3) #結果:{3,4,5,6,7} s3 = s1-s2 #差集 print(s3) #結果:{3} s3 = s1^s2 #反交集 print(s3) #結果:{3,6,7} s=set("hello")#set(字串) :把字串拆解成集合 print(s) #結果:{'h','e','o',l} 字串不會重複 print('h' in s) #結果:True print('b' in s) #結果:False ``` #### 字典運算 key-value ```python= dic = {"apple":"蘋果","bug":"臭蟲"} print(dic["apple"]) #結果:蘋果 dic["apple"] = "小呀小蘋果" #更改apple的值 print(dic["apple"]) #結果:小呀小蘋果 print("apple" in dic)#判斷key是否存在 #結果:True del dic["apple"] #刪除字典中的鍵對值(key-value pair) print(dic) #結果:{'bug':'蟲蟲'} ``` ##### 列表產生字典 ```python= #以列表當基礎產生字典 dic = {x:x*2 for x in [3,4,5]} print(dic) #結果:{3:6 ,4:8 ,5:10} ``` ## 流程控制 python目前不支援switch語法 ### 判斷式if ```python= x = input("input num:")#基本輸入為字串型態 x = int(x)#轉換成int型態 if x>200: print("大於200") elif x>100: print("大於100,小於200") else: print("小於100") ``` **實作:使用if做四則運算** ```python= n1 = int(input("input num:")) n2 = int(input("input num:")) op = raw_input("請輸入運算+-*/:") if op=="+": print(n1+n2) elif op=="-": print(n1-n2) elif op=="*": print(n1*n2) elif op=="/": print(n1/n2) else: print("不支援該運算") ``` >註解:input() 和 raw_input() 這兩個函數均能接收 字符串 ,但 raw_input() 直接讀取控制台的輸入(任何類型的輸入它都可以接收)。而對於 input() ,它希望能夠讀取一個合法的 python 表達式,即你輸入字符串的時候必須使用引號將它括起來,否則它會引發一個SyntaxError 。像是(input:"runoob") 除非對 input() 有特別需要,否則一般情況下我們都是推薦使用 raw_input() 來與用戶交換。 注意:python3 裡 input() 默認接收到的是 str 類型。 ### 迴圈基礎 #### while迴圈 實作:從1加到10 ```python= n = 1 sum = 0 while n <=10: sum+=n n+=1 print(sum) ``` #### for迴圈 ```python= #列表輸入進x for x in [4,1,2]: print(x) #結果: #4 #1 #2 #字串輸入進c for c in "hello": print(c): #結果: #h #e #l #l #o ``` ##### range 使用in range(初始,終點,運算) for x in range(3) 相當於 for x in [0,1,2] ```python= for x in range(5) print(x) #結果0 #1 #2 #3 #4 for x in range(5,10) print(x) #結果5 #6 #7 #8 #9 ``` #### 迴圈搭配的指令 break > 強制結束迴圈 一定要用在while跟for迴圈裡,且不會執行else ```python= n=1 while n<5: if n==3: break n+=1 print(n) #結果:3 ``` continue > 強制繼續下一圈 ```python= n = 0 for x in [0,1,2,3]: if x%2 == 0:#x是偶數 continue print(x) n+=1 print("跑了",n) #結果1 #3 #跑了2 ``` else > 迴圈結束前,執行此區塊的命令 ```python= sum = 0 for n in range(11): sum+=n else: print(sum) #結果:55 ``` 實作:判斷有無平方根 ```python= n = input("請輸入一個正整數") n = int(n) for i in range(n+1):#因為如果輸入1只會跑到0,但1是完全正整數 if i*i==n&n!=0:#0不是完全正整數 print("整數平方根") print(i) break#break跳出迴圈就不會執行else else: print("沒有整數平方根") #假設n=36 結果:整數平方根6 #假設n=12 結果:沒有整數平方根 ``` ## 函式 >程式碼包裝在一個區塊中,方便隨時呼叫使用 >要先定義才能呼叫 >def 函式名稱(參數名稱) ```python= def calculate(max): sum = 0 for n in range(1,max+1): sum+=n print(sum) calculate(10) calculate(20) #結果:55 #210 ``` >也可以在定義函式()預設資料 ```python= def power(base,exp=0):#預設exp=0 print(base**exp) power(3,2) power(4) #結果:9 #1 ``` >呼叫函式,可以以參數名稱對應資料,不管順序 ```python= def divide(n1,n2): print(float(n1)/float(n2)) divide(2,4) divide(n2=2,n1=4) #結果:0.5 #2 ``` **無限參數** ```python= def 函式名稱(*無限參數): #以tuple資料型態處理程式碼 函式名稱(資料一,資料二,資料三) ``` 實作 ```python= def avg(*ns): sum = 0 for n in ns: sum+=n print(float(sum)/float(len(ns))) avg(3,7) avg(3,6,9) avg(1,2,3,4) #結果:5.0 #6.0 #2.5 ``` ## Module模組載入與使用 >需先載入模組才能使用 **內建模組** ```python= import sys as s #s是別名 print(sys.path) #印出模組的搜尋路徑 ``` **自訂模組** >另外開啟資料夾modules用來放自訂模組 ```python= #自訂模組 def distance(x1,y1,x2,y2): return ((x2-x1)**2+(y2-y1)**2)**0.5 def slope(x1,y1,x2,y2): return float((y2-y1))/float((x2-x1)) ``` ```python= #匯入自訂模組 import sys as s print(s.path)#印出模組的搜尋路徑列 s.path.append("modules")#在模組的搜尋路徑中增加路徑 print(s.path) import geomentry result = geomentry.distance(1,1,5,5) print(result) result = geomentry.slope(1,3,5,6) print(result) ``` ### 亂數與統計模組 亂數模組 ```python= import python#載入亂數模組 random.choice()#隨機選取1個資料 random.sample(,n)#隨機選取n個資料 random.shuffle()#將列表資料就地隨機調換順序 random.random()#取得0.0~1.0之間的隨機亂數 random.uniform(0.0,1.0)#取得0.0~1.0之間的隨機亂數 random.normalvariate(100,10)#取得平均數100 標準差10的常態分配亂數 ``` 統計模組 ```python= import statistics statistics.mean()#計算列表中數字的平均數 statistics.median()#計算列表中數字的中位數 statistics.stdev()#計算列表中數字的標準差 ``` ## 封包設計與使用 >用來整理. 分類模組程式 >資料夾中需有__intit__.py才會被當成封包,裡面留空即可 ```python= import 封包名稱.模組名稱 as模組別名 ``` 範例:將模組放入封包資料夾 ![](https://i.imgur.com/eH9Gncv.png) ```python= #line.py def len(x1,y1,x2,y2): return (((x2-x1)**2)+((y2-y1)**2))**0.5 def slope(x1,y1,x2,y2): return float(y2-y1)/float(x2-x1) #point.py def distance(x,y): return (x**2+y**2)**0.5 #main.py import geometry.point result = geometry.point.distance(3,4) print("距離") print(result) import geometry.line result = geometry.line.slope(1,1,3,3) print("斜率") print(result) ``` ### 文字檔案讀取與儲存 檔案物件=open(檔案路徑,mode=開啟模式) >開啟模式 ```python= 檔案物件.read()#讀取全部文字 for 變數 in 檔案物件:#一次讀一行 檔案物件.write("字串\n")#寫入文字 import json#讀取json格式資料 讀取到的資料 = json.load(檔案物件) import json json.dump(要寫入的資料,檔案物件)#寫入json格式 檔案物件.close()#關閉檔案 #最佳實務 with open(檔案路徑,mode=開啟模式) as 檔案物件 #以上區塊會自動 安全的關閉檔案 ``` 範例 ```python= #儲存檔案 with open("data.txt",mode="w") as file: file.write("7\n3") #讀取檔案 #把檔案中的數字資料,一行一行的讀取出來,並計算總和 sum = 0 with open("data.txt",mode="r") as file: for line in file:#一行一行的讀取 sum+=int(line) print(sum) #結果:10 ``` ```python= #先創一個config.json {"version": "6.1.3", "name": "new name"} #使用JSON格式讀取 import json with open("config.json",mode="r") as file: data=json.load(file) print(data)#data是字典類別 print("name", data["name"])#像字典一樣讀取 print("version", data["version"])#像字典一樣讀取 data["name"] = "new name" #修改變數中的資料 print(data) #把最新資料覆寫回檔案中 with open("config.json",mode="w")as file: json.dump(data,file) print(data) ``` ## 網路連線 公開資料串接 #### 下載特定網址資料 ```python= import urllib.request as request with request.urlopen(網址) as response data = response.read() print(data) ``` ```python= # coding: utf-8 import ssl ssl._create_default_https_context = ssl._create_unverified_context # import urllib.request as request # src = "https://www.ntu.edu.tw/" # with request.urlopen(src) as response: # data = response.read().decode("utf-8") #取得胎灣大學網頁得原始碼(html.cs.js) # print(data) import urllib.request as request import json src2 = "https://data.taipei/api/v1/dataset/296acfa2-5d93-4706-ad58-e83cc951863c?scope=resourceAquire" with request.urlopen(src2) as response: data = json.load(response) #利用json模組處理json資料格式 #print(data) #將公司名稱列表出來 clist = data["result"]["results"] with open("data.txt","w",encoding="utf-8") as file: #print(clist) for company in clist:#讀取clist進company file.write(company["公司名稱"]+company["公司地址"]+"\n") ``` ## 類別的定義與使用 #### 封裝變數與函式 封裝的變數或函式,統稱類別的屬性 先定義才能使用 ```python= #定義test類別 class test: x=3 #定義變數 def say(): #定義函式 print("hello") #使用test類別 test.x+3#取得屬性x的資料3 test.say()#呼叫屬性say函式 #定義一個類別IO 有兩個屬性supportedSrcs和read class IO: supportedSrcs = ["console","file"] def read(src): if src not in IO.supportedSrcs: print("not supported") else: print("read from",src) #使用類別 print(IO.supportedSrcs) IO.read("file") IO.read("internet") ``` #### 實體物件的建立與使用 先建立實體物件,才能使用實體屬性 ```python= class 類別名稱: #定義初始化的函式 def __init__(self): 透過操作self來定義實體屬性 #建立實體物件,放入變數obj中 obj=類別名稱() #呼叫初始化函式 ``` ```python= class point: def __init__(self): self.x=3 self.y=4 #建立實體物件 #此實體物件包含x和y兩個實體屬性 p=point() ```