備忘錄_20160105(定位) 修改 回首頁

程式 2026-03-24 16:58:22 1774342702 100
python 閱讀記錄

python 閱讀記錄

[terminal] pwd (print working directory) cd (change directory) ls / dir python --version [數值]  整數 mysql, mssql, javascript, php, python 浮點數 mysql, mssql, javascript, php, python 十進位 mysql, mssql, python(decimal.Decimal)  字串 mysql, mssql, javascript, php, python 布林值 mysql, javascript, php(true/false), python(True/False) [python] 基本數學運算 +-*/ 其他數學運算 次方(2 ** 3=8) 取餘數(17 % 3=2) 整數除法(27 // 4=6) 字串 str1 = "good" str2 = "It's good!" str3 = 'It\'s good!' str4 = str1 + str2 str5 = str3 * 3 (重覆三次) strL = str2.lower() strU = str2.upper() iLen = len(str2) 註解 # 井字號後面都是註解的空間 條件判斷 if a!=b or z==8: dothis~ elif c==d and e>5: dothis~ elif not isGood: dothis~ else: final~ 條件判斷(python3.10以上) str2 = "happy" match str2: case "sad" | "cry": print("SO BAD!") case "happy" | "smile": print("VERY GOOD!") 三元運算子 str3="x" str4="Got X" if str3=="x" else "Other words!" print(str4) 串列 list lst1=[] lst2=["apple", "flower", "orange"] print("data", lst2[0]) lst2[-1] #倒數第一個項目 lst1.append("car") lst1.insert(0, "mouse") lst1.remove("basketball") lst1.pop() #刪最後一個 lst1.pop(0) #刪第零個 lst1.clear() lst1[0]="asd" lst3=lst1[2,6] #抓索引2,3,4,5 iLen1=len(lst1) booInside="flower" in lst1 元組 tuple tpl1=() str2=("just on item") tpl2=("just on item",) # 多加一個逗號才會變元組,但此元組長度為1 tpl3=(18,"charly",40,160) iAge=tpl3[0] strName=tpl3[1] fWeight=tpl3[2] fHeight=tpl3[3] 解封 unpacking (list, tuple都通用) iAge, strName, fWeight, fHeight = [18,"charly",40,160] iAge, strName, fWeight, fHeight = (18,"charly",40,160) 字典 dictionary (鍵:値) dic1={} # 只有 strings, tuples, numbers 可以當鍵 dic2={"name":"charly", "age":18, "weight":40, "height":170} strMyName=dic2["name"] # 傳回 "charly" strMyName=dic2.get("name") # 傳回 "charly" strUnknown=dic2["unknown"] # 產生 KeyError 錯誤 strYesOrNo=dic2.get("yesorno") # 傳回 None strImpossible=dic2.get("impossible", "找不到") # 傳回 "找不到" dic3={"seq":0, "note":"nothing", "name":"QB"} dic3["address"]="臺中市西區某某路某某號" # 新增 dic3["seq"]=1 # 修改 del dic3["note"] # 刪除 del dic3["trouble"] # 產生 KeyError 錯誤 seq=dic3.pop("seq") # 提取値後,移除此鍵 pqr=dic3.pop("pqr") # 產生 KeyError 錯誤 xyz=dic3.pop("xyz","找不到") # 傳回 "找不到" lstKey=list(dic3.keys()) # 傳回 ['name', 'address'] lstVal=list(dic3.values()) # 傳回 ['QB', '臺中市西區某某路某某號'] lstKV=list(dic3.items()) # 傳回 [('name', 'QB'), ('address', '臺中市西區某某路某某號')] booKeyExist="address" in dic3 # 將傳回 True 迴圈 while i=0 while i<5: i=i+1 name = input("What is your name? ") print("Hello", name) 迴圈 for # sequence 可以是 list, tuple, range for variable in sequence: # 要執行的程式 for i in range(5): print(i) # 這會列印 0 ~ 4 # range(5) → 0,1,2,3,4 # range(0,5) → 0,1,2,3,4 # range(0,5,2) → 0,2,4 # range(5,1,-2) → 5,3 # # range(start包含, stop不含, step) for item in list: ...... for item in tuple: ...... for key in dictionary: ...... for key, value in dictionary.items(): print(key +": "+value) # 記得 break 和 continue for variable in condition: # 區塊一 else: # 區塊二 (若迴圈能完整跑完,則執行此區塊;若遇 break,則不會執行) # 注意,若是迴圈的過程中,對 condition 有增減動作的話,可能會出事的! # 用副本的方式操作,比較不會出事。 numbers = [1, 2, 2, 3, 4, 4, 5] for num in numbers[:]: if num == 2: numbers.remove(num) print(numbers) 函式 (範例) def sayyes(fname,lname): print(fname+' '+lname+' says yes!') sayyes('Charly','Whang') 函式 (範例:回傳處理) def check(i,j,k): if i==3: return (i+1, j+1, k+1) rtn1=check(1,2,3) # 得到 None if rtn1 is None: print('got None') if rtn1 is not None: print('something') rtn2=check(3,4,5) # 得到 (4,5,6) x,y,z=rtn2 # x=4, y=5, z=6 函式 (範例:預設參數) def saveItem(name, value="normal"): ...... 函式 (範例:關鍵字引數) def saveMoney(name, amount, note="nothing"): ...... saveMoney(amount=10000, name="John") 函式 (範例:不固定長度引數) def show1(*args): print(args) def show2(**kwargs): print(kwargs) def show3(*args, **kwargs): print(args, kwargs) def notworked(**kwargs, *args): # 這個行不通,關鍵字引數只能往後放 print(args, kwargs) show1("stone", "water", "fire") # 這會印出tuple ("stone", "water", "fire") show2(element1="stone", element2="water", element3="fire", element4="air") # 這會印出dictionary {"element1":"stone", "element2":"water", "element3":"fire", "element4":"air"} show3(1,2,3,4,5,6,7,note="good",fly="yes") # 這會印出 (1,2,3,4,5,6,7){"note":"good", "fly":"yes"} 變數作用範圍 # 函式內可以讀到全域變數,但不能修改。 # 本範例會得到兩個 10 x=10 def play1(): print(x) play1() print(x) # 函式內宣告同名變數,會是區域變數。 # 本範例會得到兩個 10 x=10 def play1(): x=20 print(x) play1() print(x) # 函式內宣告同名變數,會是區域變數。 x=10 def play1(): print(x) # 這個程式會出錯誤,因為給定值之前就先使用 x=20 print(x) play1() print(x) # 函式內明確宣告使用全域變數,這時候可以讀寫變數 # 得到 10,20,20 x=10 def play1(): global x print(x) x=20 print(x) play1() print(x) 內建函數 type, int, float, str i1=3 print(type(i1)) # <class 'int'> str1=str(i1) print(type(str1)) # <class 'str'> f1=float(str1) i2=int(str1) 模組 ------ mymodule.py ------ def func1(): ...... def func2(x,y,z): ...... ------ main1.py ------ import mymodule mymodule.func1() mymodule.func2(3,4,5) ------ main2.py ------ from mymodule import func2 func2(6,7,8) ------ main2.py ------ import mymodule as mm mm.func2(6,7,8) 一些模組 import math x=math.sqrt(25) # 得 5 y=math.pow(2, 4) # 得 16 z=math.factorial(5) # 得 5!=120 # 其他 r1=math.radians(90) 角度換成弧度 # 其他 math.sin(radians), math.cos(radians), math.tan(radians) # 其他 math.log(x), math.log10(x), math.ceil(x), math.floor(x) # 其他 math.pi, math.e # 其他 cmath 模組, decimal 模組, random 模組 亂數模組 import random x=random.randint(1,6) # 6是有包含在內的 while x!=6: print(x) x=random.randint(1,6) import random x=random.random() # [0,1) 不包含1 while x!=0: print(x) x=random.random() pets=["Maja", "Clonde", "Harve"] chosen_pet=random.choice(pets) random.shuffle(pets) # 會洗牌弄亂順序 s=random.sample(pets, 2) # 任取兩個當樣本 日期時間模組 from datetime import datetime, timedelta now=datetime.now() # 有年月日時分秒 anotherday=now+timedelta(days=3) print(now.year, now.month, now.day, now.hour, now.minute, now.second) print(anotherday) 說明文字 def func1(x,y,z): """ 這是說明文字 第二行也縮排喔 """ return (x+y+z) 路徑 import os strFolder="images" strFileName="img01.jpg" strFilePath=os.path.join(strFolder, strFileName) 檔案 oFile=open("filename.txt", "r") oFile.close() r → 讀取文字檔 rb → 讀取二進位檔 w → 覆寫檔案 a → 新增檔案 # 使用 with ,檔案會自動關閉 with open("filename.txt", "r") as oFile: strContent=oFile.read() print(strContent) read() → 讀入全部 readline() → 讀取一行 readlines() → 讀入全部,放到 list 中 open("filename.txt", "r", newline=None) # (預設) \r\n, \r, \n 通通都會變成 \n,之後認定是換行符號 open("filename.txt", "w", newline=None) # (預設) \n → (windows)\r\n 或 (linux)\n open("filename.txt", "r", newline="") # \r\n, \r, \n 不會改變,都是換行符號 open("filename.txt", "w", newline="") # 完全不做更動 open("filename.txt", "r", newline="\r") # 只有 \r 是換行符號, \n 算一般字元 open("filename.txt", "w", newline="\r") # 將所有的 \n 通通換成 \r read(), readline(), readlines() 讀到的字串,都會保留換行符號,這一點特別不同,要留意。 所以要判斷是否讀到檔案結尾,就看是否為空字串,就知道了。 nmomtf - readline() to read the file one line at a time