python 基礎筆記

python 基礎筆記

這是筆者自己的python 基礎代碼的學習筆記。老人初學入門。文件以繁體中文編輯。
如有錯誤請指教。

一. 資料

資料類別

  1. 數值資料(int): ex= 120
  2. 字串資料(str): ex= "陳大文”
  3. 布林資料(bool): ex=Ture / ex= False

強制資料型態轉換/特定格式化

  • int(變數1) # 強制變數1為整數 eg:1,2,3
  • float(變數1) # 強制變數1為浮點數 eg:3.1416
  • str(變數1) # 強制變數1為字串

資料組合

  1. list (有次序結構)
list1=["APPLE","PEAR","ORANGE","WATERMELON"]
list2=[1,22,334,32,99]
  1. tuple (有次序結構,不能改變)
tuple1=("APPLE","PEAR","ORANGE","WATERMELON") 
tuple2=(1,22,334,32,99)
  1. dict (無次序結構):{key:value}
dict1={"豬肉":100,"牛肉":130,"羊肉":140,"海魚":120}

實例:

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}
  1. Multi-dimension list
md_a = [[1,2,3],
        [4,5,6],
        [7,8,9]]
print (md_a[1][1]) #5
  1. pandas(pd) & numpy(np)常見數據組合
  • array (from numpy, 有次序結構、Matrix)
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]
  • pd.DataFrame

算術運算子及邏輯運算子

算術運算子

符號意義及例子結果
+6+39
-6-33
*6*318
/6/32
//整除後商數: 32%56
%整除後餘數: 32%52
**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+= 2a=a+2
-=a -= 2a=a-2
*=a *= 2a=a*2
/=a /= 2a=a/2
%=a %=2if a1=10, a%=2, a2=0
//=a //=2if a1=10, a//=2, a2=5
**=a **=2if a1=10, a**=2, a2=100

進階數據列組合

進階串列

Let: list1=[1,2,3,4,5], list9=[8,9]

語法意義例子例子結果
list(Xn)Xn的元素變成Listb =list(FishC)b =[’F’,’i’,’s’,’h’,’C’]
list1*n串列重覆n次list2=list9*2list2=[8,9,8,9]
list1[n1:n2]取串列中n1至n2-1位元list2=list1[1:4]list2=[2,3,4]
list[n1:n2:n3]同上,間隔為n3list2=list1[0:4:2]list2=[1,3]
如n3是負數,由最後取間隔list2=list1[::-2]list2=[5,3,1]
del list1[n1:n2]刪n1至n2-1del list1[0:4]list1=[1,5]
del list1[n1:n2]同上,間隔為n3del 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()串列由小至大排序

進階dict

Let: dict1={“豬肉”:100,”牛肉”:130,”羊肉”:140,”海魚”:120} , dict9={”淡水魚”:110,水果:50}

語法意義例子例子結果
len(dict1)取得dict內元素數目n=len(list1)n=4
dict1.clear(n1)刪除dict內n1元素dict1.clear(“海魚”)
刪除dict內所有元素dict1.clear()
dict1.copy()覆製dictdict2=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 dict1b=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 close

字符串列相關指令 (str_list.xxxxx())

指令說明
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)

基本顯示 (print, sep, end, format, type)

print

# 語法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位
脫逸字元 (print()時用
code指示
\標點該標點為標點而非語法
\r游標移到列首
\n換行
\v垂直定位
\tTab
\f換頁
\bBackspace
\a響鈴
\x以十六進位表示字元
\o以八進位表示字元

type

print (type(18))		#<class 'int'> 		  
print (type('陳大文'))	#<class 'str'> 
print (type(True))		#<class 'bool'>

條件控制 (input、運算、條件式)

input

age = input (“請輸入你的年齡:”)  #「請輸入你的年齡:」,假設輸入 18
print (age)  # 18

if … elif …else

例子1: 密碼(簡單一次性運作)

pw = int(input ('請輸入密碼:'))
if (pw == 123456):
    print ('Welcome')
else:
    print ('Wrong Password')

例子2: 折扣查詢 Let:消費$5000或以上7折,$3000以上8折,$1000以上9折,其他95折

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")
assert (斷言)

用法與if 相似,但assert 後的條件式必須為真,否則會顯示 “AssertionError”。

循環/廻圈 (for, in, range, break, continue, for…else, while)

例子1: 九九乘數

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 (整數值) #range為0至 整數值-1
range (起始值, 終止值) #range為起始值 至 終止值-1
range (起始值, 終止值, 間隔值)
例子:

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, continue

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 … else

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

當在條件式內,循環;否則(否定條件) 結束循環。

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 及 class

大程式中的(各個)小單元,例如常用程式碼。其好處:

  1. 方便分工開發
  2. 把常用程式碼成為一個函式,可減縮方度及方便重覆使用
  3. 提高可讀性,以便除錯及維護

def 自定函式

語法:

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)" )
不定量參數函式(如for)

def 函式名稱(*X):
例子4:

def calsum(*params)
    total =0
    for param in params:
        total += param
    return total
變數有效範圍

分為區域變數(定義一個函式的變數,在該函式/該層函式有效)

def scope():

class (類)

用來描述具有相同的屬性和方法的對象的集合。它定義了該集合中每個對象所共有的屬性和方法。對象是類的實例。

  • 方法:類中定義的函數。
  • 類變量:類變量在整個實例化的對象中是公用的。類變量定義在類中且在函數體之外。類變量通常不作為實例變量使用。
  • 數據成員:類變量或者實例變量用於處理類及其實例對象的相關的數據。
  • 方法重寫:如果從父類繼承的方法不能滿足子類的需求,可以對其進行改寫,這個過程叫方法的覆蓋(override),也稱為方法的重寫。
  • 局部變量:定義在方法中的變量,只作用於當前實例的類。
  • 實例變量:在類的聲明中,屬性是用變量來表示的。這種變量就稱為實例變量,是在類聲明的內部但是在類的其他成員方法之外聲明的。
  • 繼承:即一個派生類(derived class)繼承基類(base class)的字段和方法。繼承也允許把一個派生類的對象作為一個基類對象對待。例如,有這樣一個設計:一個Dog類型的對象派生自Animal類,這是模擬"是一個(is-a)"關係。
  • 實例化:創建一個類的實例,類的具體對象。
  • 對象:通過類定義的數據結構實例。對象包括兩個數據成員(類變量和實例變量)和方法
    例子1:
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( )乘方

import 套件(package/ module)

調用語法:

#----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

open('filename', 'mode')

'mode’參數:

參數功能
r以read only方式打開文件。文件的指針將會放在文件的開頭。默認。
wwrite only,如文件已存在則從開頭開始編輯,即原有內容會被删除。如果該文件不存在,創建新文件。
awrite 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

read(), readline(), readlines()

承上例子

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檔存檔

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

(要先安裝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 位置及檔案名
requests
import requests
file1=requests.get(url)
with open(saveas,'wb') as f:     
    f.write(file1.content)
urllib
from urllib.request import urlopen
filedata=urlopen(url)
datatowrite=filedata.read()
with open(savesa,'wb') as g:
    g.write(datatowrite)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值