這是筆者本身的python 基礎代碼的學習筆記。老人初學入門。文件以繁體中文編輯。
若有錯誤請指教。python
list1=["APPLE","PEAR","ORANGE","WATERMELON"] list2=[1,22,334,32,99]
tuple1=("APPLE","PEAR","ORANGE","WATERMELON") tuple2=(1,22,334,32,99)
dict1={"豬肉":100,"牛肉":130,"羊肉":140,"海魚":120}
實例:git
dict1={"豬肉":100,"牛肉":130,"羊肉":140,"海魚":120} dict1 ["牛肉"]=140 print (dict1["牛肉"]) #140 dict1 ["淡水魚"]=110 print (dict1) #{'豬肉:100,'牛肉':140,'羊肉':140,'海魚':120,'淡水魚':110} del dict1 ["淡水魚"] 或 dict1.clear("淡水魚") print (dict1) #{'豬肉': 100, '牛肉': 140, '羊肉': 140, '海魚': 120}
md_a = [[1,2,3], [4,5,6], [7,8,9]] print (md_a[1][1]) #5
import numpy as np a1 = np.array([[3,8,21], [9,4,11]]) #e.g. b1 = np.array([3,8,21]) b2 = np.array([9,4,11]) print (b1*b2) #[27 32 231]
符號 | 意義及例子 | 結果 |
---|---|---|
+ | 6+3 | 9 |
- | 6-3 | 3 |
* | 6*3 | 18 |
/ | 6/3 | 2 |
// | 整除後商數: 32%5 | 6 |
% | 整除後餘數: 32%5 | 2 |
** | 9**2 = | 81 |
** | 9**0.5= | 3 |
符號 | 意義及例子 | 結果 |
---|---|---|
== | 左右全等(3+6 == 2+10) | False |
!= | 左右不等(3+6 != 2+10) | True |
> | (3+6 > 2+10) | False |
< | (3+6 < 2+10) | True |
>= | (3+6 >= 2+10) | False |
<= | (3+6 <= 2+10) | True |
not | 邏輯運算子的 ~ : not(3+6 > 2+10) | True |
and | 邏輯運算子的 ∙:(3<6) and (2<10) | True |
or | 邏輯運算子的 ∨:(3>6) or (2<10) | True |
in | 指定值在list中 >>>list1=[1,2,3] >>>a=10,if (a in list1) | False |
not in | (反之) | True |
符號 | 意義及例子 | 結果 |
---|---|---|
+= | a+= 2 | a=a+2 |
-= | a -= 2 | a=a-2 |
*= | a *= 2 | a=a*2 |
/= | a /= 2 | a=a/2 |
%= | a %=2 | if a1=10, a%=2, a2=0 |
//= | a //=2 | if a1=10, a//=2, a2=5 |
**= | a **=2 | if a1=10, a**=2, a2=100 |
Let: list1=[1,2,3,4,5], list9=[8,9]web
語法 | 意義 | 例子 | 例子結果 |
---|---|---|---|
list(Xn) | Xn的元素變成List | b =list(FishC) | b =[’F’,’i’,’s’,’h’,’C’] |
list1*n | 串列重覆n次 | list2=list9*2 | list2=[8,9,8,9] |
list1[n1:n2] | 取串列中n1至n2-1位元 | list2=list1[1:4] | list2=[2,3,4] |
list[n1:n2:n3] | 同上,間隔為n3 | list2=list1[0:4:2] | list2=[1,3] |
如n3是負數,由最後取間隔 | list2=list1[::-2] | list2=[5,3,1] | |
del list1[n1:n2] | 刪n1至n2-1 | del list1[0:4] | list1=[1,5] |
del list1[n1:n2] | 同上,間隔為n3 | del list1[0:4:2] | list1=[2,4,5] |
n=len(list1) | 串列內元素數目 | n=len(list1) | n=5 |
n=min(list1) | 串列內元素最小值 | n=min(list1) | n=1 |
n=max(list1) | 串列內元素最大值 | n=max(list1) | n=5 |
n=list1.index(n1) | 首個n1元素的索引值 | n=list1.index(3) | n=2 |
n=list1.count(n1) | n1元素在list1的頻數 | n=list1.count(3) | n=1 |
list1.append(ni) | 將ni元素加在串列最後 | list1.append(9) | list1=[1,2,3,4,5,9] |
list1.append([8,9]) | list1=[1,2,3,4,5,8,9] | ||
list1.extend(x) | 將串列x的元素,加在串列最後 | list1.extend(list9) | list1=[1,2,3,4,5,8,9] |
list1.insert(n,n1) | 在n 位置加入n1元素 | list1.insert(2,9) | list1=[1,2,9,3,4,5] |
n=list1.pop() | 取出串列指定元素為n, 並在串列中刪去該元素。()預設為最後一個元素 | n=list1.pop() | n=5; list1=[1,2,3,4] |
list1.remove(n) | 刪除首個n元素 | list1.remove(3) | list1=[1,2,4,5] |
list1.reverse() | 串列反序 | list1=[5,4,3,2,1] | |
reversed(list1) | 同上 | list1=[5,4,3,2,1] | |
list1.sort() | 串列由小至大排序 |
Let: dict1={“豬肉”:100,”牛肉”:130,”羊肉”:140,”海魚”:120} , dict9={”淡水魚”:110,水果:50}json
語法 | 意義 | 例子 | 例子結果 |
---|---|---|---|
len(dict1) | 取得dict內元素數目 | n=len(list1) | n=4 |
dict1.clear(n1) | 刪除dict內n1元素 | dict1.clear(“海魚”) | |
刪除dict內全部元素 | dict1.clear() | ||
dict1.copy() | 覆製dict | dict2=dict1.copy() | |
dict1.get(k1:v1) | 取得key對應的值(k1:v1) | n= dict1.setdefault (“羊肉”) | n=140 |
若有key但錯value,取原value;key不存在, v1為預設值 | n= dict1.setdefault (“羊肉”,100) | n=140 | |
n= dict1.setdefault (“蛇肉”) | n=None | ||
n= dict1.setdefault (“蛇肉”,200) | n=200 | ||
dict1.setdefault(k1:v1) | 取得key對應的值,如(k1:v1)有key但錯value,取原value;key不存在,dict1加入(k1:v1) | n= dict1.setdefault (“羊肉”) | n=140 |
n= dict1.setdefault (“羊肉”,100) | n=140 | ||
n= dict1.setdefault (“蛇肉”)“蛇肉” | n=None,dict1加蛇肉 | ||
n= dict1.setdefault (“蛇肉”,200) | n=200,dict1[""]=200 | ||
x= key in dict1 | 檢查key 是否在dict內 | b= “羊肉” in dict1 | b=True |
x=dict1.items(k1:v1) | 在dict1中抽出(k1:v1 )組為元素組合 | dict2= dict1.items() | dict2=[(‘豬肉’,100),(‘牛肉’,130),(‘羊肉’,140),(‘海魚’,120)] |
x=dict1.keys() | 取得key對應的組合(串列) | list1=dict1.keys() | list1= [‘豬肉’, ‘牛肉’, ‘羊肉’, ‘海魚’] |
x=dict1.values() | 取得values對應的組合(串列) | list1=dict1.values() | list1=[100,130,140,120] |
數算:acos asin atan cos sin tan pi lambda sqrt log log10 e
條件:if elif else assert while for break continue try except
類型:int float str array range type global in is not and or
指令:import as input from class def return print exec exp fabs
finally floor data pass raise zeros del
存取:open read write closeapi
指令 | 說明 |
---|---|
capitalize() | 各字符的第一個字母為大寫,其余為小寫 |
casefold() | 全小寫 |
center(width[,fillchar]) | 置中,width=預設宽度字元數 |
count(sub[,start[,end]]) | |
encode(encoding=’xx’,errors=’strict’) | 指定編碼格式(例如:utf-8)對字符串編碼;error編碼 |
endwith(sub[,start[,end]]) | 檢查字符串 |
expandtabs(tabsize=X) | |
find(sub[,start[,end]]) | |
rfind(sub[,start[,end]]) | |
index(sub[,start[,end]]) | |
rindex(sub[,start[,end]]) | |
ljust(width[,fillchar]) | |
rjust(width[,fillchar]) | |
lower() | 字符串小寫化(全部字母為小寫) |
islower() | 檢查字符串是否小寫化:True or False |
upper() | 字符串大寫化(全部字母為大寫) |
isupper() | 檢查字符串是否大寫化:True or False |
title() | 字符串標題化(全部字首字母為大寫) |
istitle() | 檢查字符串是否標題化:True or False |
partition(sep) | |
rpartition(sep) | |
strip([chars]) | |
rstrip([chars]) | |
lstrip([chars]) | |
isalnum() | 檢查字符串是否只由字母或數字構成:True or False |
isnumeric() | 檢查字符串是否只由數值構成:True or False |
isalpha() | 檢查字符串是否只由字母構成:True or False |
isdecimal() | 檢查字符串是否只由十進制數字構成:True or False |
isdigit() | 檢查字符串是否只由數字構成:True or False |
isspace() | 檢查字符串是否只由空白字符構成:True or False |
join(iterable) | |
replace(old, new[,count]) | |
split(sep=None,maxspit=-1) | |
splitlines([keepends]) | |
startwith(prefix[,start[,end]]) | |
swapcase() | |
translate(table) | |
zfill(width) |
# 語法1 print (變數1,變數2,…,sep= "分融字元",end="") #1 #例子1 print (100, '陳大文', sep='&', end='') # 100&陳大文 #語法2 print ('%... %...' %(參數列)) #或 print ('{}…{}…'.format (參數列)) #例子2 name ='陳大文' age=18 sex='男' print('%s為%d歲的%s生' %(name, age, sex)) # 或 print('{}為{}歲的{}生' .format (name, age, sex)) # 陳大文為18歲的男生 #註:%s為字符, %d為數字;%5d為固定列印5字元,不足5字元左補白字元 #語法3 print (…%特定格式 %(參數列)) #例子3 price= 23.6756 print("價格為 %5.2f" %(price)) #價格為 23.68 #註:%5.2f為(a)'%5'列印5字元,不足5字元左補白字元;(b)'.2f'小數點後2位
code | 指示 |
---|---|
\標點 | 該標點為標點而非語法 |
\r | 游標移到列首 |
\n | 換行 |
\v | 垂直定位 |
\t | Tab |
\f | 換頁 |
\b | Backspace |
\a | 響鈴 |
\x | 以十六進位表示字元 |
\o | 以八進位表示字元 |
print (type(18)) #<class 'int'> print (type('陳大文')) #<class 'str'> print (type(True)) #<class 'bool'>
age = input (“請輸入你的年齡:”) #「請輸入你的年齡:」,假設輸入 18 print (age) # 18
例子1: 密碼(簡單一次性運做)app
pw = int(input ('請輸入密碼:')) if (pw == 123456): print ('Welcome') else: print ('Wrong Password')
例子2: 折扣查詢 Let:消費$5000或以上7折,$3000以上8折,$1000以上9折,其余95折ide
money= input("請輸入消費金額:") #或 money=float(input('.....')) money= float(money) # 如用上列語法,本行省略 if (money >= 5000): print("消費可享7折,折扣後金額為" + str(money * 0.7), end="元\n") elif money >= 3000: print("消費可享8折 折扣後金額為" + str(money * 0.8), end="元\n") elif money >= 1000: print("消費可享9折 折扣後金額為" + str(money * 0.9), end="元\n") else: print("消費可享95折,折扣後金額為" + str(money * 0.95), end="元\n")
用法與if 类似,但assert 後的條件式必須為真,否則會顯示 “AssertionError”。svg
例子1: 九九乘數ui
for y in range(1,10): #首層 for z in range(1,10): #次層 p = y * z #首次層計算 print ("%1dX%1d=%-2d" %(y,z,p), end="\n") #輸出格式 print() #首次層輸出
range (整數值) #range為0至 整數值-1
range (起始值, 終止值) #range為起始值 至 終止值-1
range (起始值, 終止值, 間隔值)
例子:url
range(5) # list5 =[0,1,2,3,4] range(0,5) # list5 =[0,1,2,3,4] range(4,10,2) # list5 =[4,6,8]
break:在for 循環中,當變數對應到指定的條件式(if),程序中斷
continue:在for 循環中,當變數對應到指定的條件式(if),跳過該條件繼續程序 (似skip)
例子1:樓層數 (只跳 fourth floor)
n = int(input("Please input the hightest floor of the buliding:")) print("The building has these levels:") n += 1 for i in range(1, n): if (i==4): continue print(i, end=" ") print ()
例子2:樓層數 (跳全部"4"字尾,但非continue 或 break)
n = int(input("Please input the hightest floor of the buliding:")) blocklevel=[] alllevel=[] a = n//10 #或二式: a=((n//10)+1)*10 b = (a+1)*10 #如用二式,刪 for x in range(4,b,10): #如用二式,b改a blocklevel.append(x) #list n += 1 for i in range(1, n): if not i in blocklevel: alllevel.append(i) print("The building has these levels:") print (alllevel)
for 循環在沒有觸及if 的條件下,繼續。
語法:
for 變數 in 串列/range: 程式1 If (條件式): 程式2 break else: 程式3
例子:質數判斷
n = int(input("請輸入大於1整數:")) assert n>1 , '輸入整數必須大於1' if (n == 2): print("%d是質數" %n) else: for k in range(2, n): if (n % k == 0): print("% d不是質數" % n) break else: print(" % d是質數" % n)
當在條件式內,循環;否則(否认條件) 結束循環。
while (條件式): 程式1
例子:多個學生成績平均數計算 (經修改)
n, t , p, score = 0,0,0,0 n = int(input("請輸入學生數目:")) while p != n: p += 1 score = int(input("請輸入第%d學生的成績:" %p)) t += score mean = t / n print("本班學生數為%d人,總成績為%d,平均分為 %d" % (n, t, mean))
大程式中的(各個)小單元,例如经常使用程式碼。其好處:
語法:
def defpart(X1,X2,...,Xn ): #或 def defpart( ): 程式區塊 #或 def defpart(X1,X2,…,Xi): #<--以"函式名稱"叫出函式 程式區塊 return ver1 #<--程式區塊內計算ver1並做為輸出值 # Load def defpart (a,b,,..,n) #或 defpart (X1=a,X2=b,,..,Xn=n)
例子1:
def fun(a,b,c): summ= a+b+c print ("a+b+c=",summ) fun (3,5,6) #or fun(a=3,b=5,c=6) # a+b+c= 14
函式创建後不會自動執行,必須在主程序中呼叫函式名稱。下列為固定參數函式
例子2: 攝氏轉華氏
def excf(cd): #計算式 fd = cd * 1.8 + 32 return fd #---main code---# inputc=end=0 while end != 1: inputc= float(input("請輸入攝氏溫度:")) print("華氏温度為:%5.1f度" %excf(inputc)) #用 end= int(input("是否繼續[離開按1; 繼續按其余]")) print ("歡迎使用")
例子3: 體積計算
def vol(width,length,height): return width*length*height def print_welcome(name): print("It is a/an", name) #---main code---# in_name=str(input("Please input the name of the object: ")) w= int(input("Please input the width(in mm):")) l= int(input("Please input the length(in mm):")) h= int(input("Please input the height(in mm):")) assert w>0, print ("The width must be greater than 0") assert l>0, print ("The length must be greater than 0") assert h>0, print ("The height must be greater than 0") volmm=vol(w,l,h) volcm=volmm/(10*10*10) print_welcome(in_name) print("width =",w, "length=",l, "height =",h," volume =",volmm,"mm**3 or",volcm,"cm**3)" )
def 函式名稱(*X):
例子4:
def calsum(*params) total =0 for param in params: total += param return total
分為區域變數(定義一個函式的變數,在該函式/該層函式有效)
def scope():
用來描述具备相同的屬性和方法的對象的集合。它定義了該集合中每個對象所共有的屬性和方法。對象是類的實例。
class Cal1 name= ‘Calculator’ price=180 def plus(self, x,y) print (self.name) print (x+y) def minus (self, x,y) print (x-y) def times (self, x,y) print (x*y) def div (self, x,y) print (x/y) #---LOAD the module (*.py)---# >>>call= Cal1() >>>call.name Calculator >>>call.plus(3,5) Calculator 8
例子2:
class Test1: def __init__(self, name, price, new_car) #class的特殊方法(構造方法) self.n = name self.price = price self.new = new_car #---LOAD the module (*.py)---# >>>x=Test1(‘Toyoto’, ‘180000’, True) #實例化 >>>x.n Toyoto >>>x.price 18000
函數 | 用途 |
---|---|
init( ) | 構造函數,在生成對象時調用 |
del( ) | 析構函數,釋放對象時使用 |
repr( ) | 打印,轉換 |
setitem( ) | 按照索引賦值 |
getitem( ) | 按照索引獲取值 |
len( ) | 獲得長度 |
cmp( ) | 比較運算 |
call( ) | 函數調用 |
add( ) | 加運算 |
sub( ) | 減運算 |
mul( ) | 乘運算 |
truediv( ) | 除運算 |
mod( ) | 求餘運算 |
pow( ) | 乘方 |
調用語法:
#----eg1----# import time print (time.localtime()) #----eg2----# import time as t #把指定套件取一個簡短的別稱 print (t.localtime()) #----eg3----# from time import localtime, time #引入time 模塊中的localtime和time的功能 print (localtime()) print (time()) #----eg4----# from time import * #引入time 模塊中的全部功能 print (localtime()) print (time())
open('filename', 'mode')
'mode’參數:
參數 | 功能 |
---|---|
r | 以read only方式打開文件。文件的指針將會放在文件的開頭。默認。 |
w | write only,如文件已存在則從開頭開始編輯,即原有內容會被删除。若是該文件不存在,創建新文件。 |
a | write only,若是該文件已存在,文件指針將會放在文件的結尾。即新的內容將會被寫入到已有內容之後。若是該文件不存在,創建新文件進行寫入。 |
r+ , w+, a+ | 讀+寫。其余同 r, w, a |
rb, wb, ab | 以二進制格式的r,w,a |
rb+,wb+,ab+ | 以二進制格式r+,w+,a+ |
例子:
text = "Hello,Apple!\n See you tomorrow!\n" myfile = open('file1.txt','w') #打開file1.txt, write only myfile.write(text) #寫入text 的值(文字) myfile.close() #關閉file1.txt
承上例子
rf = open(file1.txt,'r') str1= rf.read() #Hello,Apple! See you tomorrow! str2= rf.readline() #Hello,Apple! str3= rf.readlines() #[Hello,Apple!/n See you tomorrow!/n]<-變成list rf.close()
JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式
import json data1 = { #json格式與python字典格式極类似 'a':1, 'b':'str',… } json_data = json.dumps (data1) #python轉json data2=json.loads(json_data) #json轉python #---寫入json---# with open('data.json', 'a') as fi: #(參數參考 “open”) json.dumps (date1,fi) #存data1入fi(即'data.json') #---讀取json---# with open('data.json', 'r') as fi: #open 'data.json' (參 “open”) data3 = json.load (fi)
(要先安裝wget,Co-lib的話先輸入 !pip install wget)
import wget load = 'http://............../XXX.csv' #來源檔位置 saveas ='./data/XXX.csv' #save as 位置及檔案名 wget.downlod(load,saveas) requests or urllib url = 'http://............../XXX.csv' #來源檔位置 saveas ='./data/XXX.csv' #save as 位置及檔案名
import requests file1=requests.get(url) with open(saveas,'wb') as f: f.write(file1.content)
from urllib.request import urlopen filedata=urlopen(url) datatowrite=filedata.read() with open(savesa,'wb') as g: g.write(datatowrite)