@see python程式設計入門 -葉難
基本 保留字 and as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass print raise return try while with yield None False True
弱型態 可以是int,long,float,str,bool,list,tuple。都是object。
強制指定型態 int(3) long(123L) float(3.14) str(‘aaa’),str(3.14),str([1,2,3]),str([]),str(()),str(True),str() bool(True),bool([]),bool(()),bool(‘’),bool(0),bool(0.0),bool(None) list([0,1,2,3,4,’a’,’b’]) tuple((0,1,2,3,4,’a’,’b’))
字串用’或”都可以, 預設用’ 以換行做為statement結尾。也可用分號結尾,合並多個statement。 list 從0開始 內容不需是同一種型態 list=[0,1,2,3,4,5,6] list=[‘frank’,111,3222,[‘c’,’python’]] list list[0] list[3] list[3][1] list[1]*list[2] list[1]=999 list[1] s=”wijefiwjeifj” s=’iiu2iu3i5u3iu’ s
tuple; immutable list () t=(0,1,2,3,4,5,6,7) t[0] t=(‘zero’,1,2,22.33,’kk’,(‘final’,”FINAL”)) t[5] t[5][1]
tuple注意事項 t[1]=333 #you got error to assign value on tuple oneElementStr=(‘juststr not tuple’) oneElementStr oneElementTuple=(‘only1’ ,) #need comma in the end oneElementTuple t3=’asdfw’,’aaa’,’vvvv’ #simplify expression of tuple t3
operator +-*/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 % 除法只取餘數 // 除法只取商 ** 次方 >>> 17 /3 5 >>> 17.0 /3.0 5.666666666666667 >>> >>> 'hello' + ' ' + 'world' +'!' 'hello world!' >>> 'hello' *3 'hellohellohello' >>> [1 ,2 ,3 ]*3 [1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 ] >>> [1 ,2 ,3 ]+['a' ,'b' ,'c' ][1 , 2 , 3 , 'a' , 'b' , 'c' ]
comparison operator < <= > >= != <> == in, not in for list/tuple is, is not for reference check logical comparator and, or, not boolean True, False False == () #False False == [] #False False == [‘0’] #False False == [0] #False False == (0,) #False False == ‘0’ #False False == 0 #True
False False None 0 ‘’ [] ()
True not False ‘0’ [0] (0,)
assignment 1 2 3 4 a=b=c=3 b=4 ;c=5 x=y=z=[0 ,1 ,2 ,3 ,4 ] x,y,z
serial assignment 1 2 3 4 5 6 7 (a,b,c)=(0 ,1 ,2 ) a;b;c; a,b,c=0 ,1 ,2 a,b=b,a a;b;c; [a,b,c]=[9 ,8 ,7 ] a;b;c;
star mark for only python3 1 2 3 x=[0 ,1 ,2 ,3 ,4 ,5 ] a,*b,c=x a,b,c
+= -= = /= %= //= * = >>= <<= &= ^= |= if/elif/else 使用:和tab做區塊包圍檢查 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 a,b,c=1 ,2 ,3 x=None ; if a<b: if b<c: x=c else : x=b else : if a<c: x=c else : x=a x print xprint(x)
1 2 3 4 5 a,b,c=0 ,'' ,[] if a and b and c: print('all true' ) else : pass
while 1 2 3 4 5 6 i=1 ;x=0 ; while i<100 : x+=i i+=1 i,x
for 1 2 3 4 5 6 7 8 9 scores=[23 ,54 ,52 ,55 ,99 ] total=0 n=0 for x in scores: n+=1 total+=x avg=total/n avg,total,n
for char in str 1 2 3 4 5 6 7 s='hello world' count=0 for x in s: if x=='e' : count+=1 count
serial assignment for list/tuple in for 1 2 3 4 5 6 7 nameScores=(('banana' ,32 ,55 ),('apple' ,67 ,48 ),('orange' ,72 ,8 )) highs=[] for x,y,z in nameScores: if y>30 and z>40 : highs+=[x,y,z] highs
break/continue for while/for function; def/return 1 2 3 def testfunction (param) : return 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def sum (numbers,initial) : total=initial for x in numbers: total+=x return total sum((1 ,2 ,34 ,6 ,7 ),0 ) sum([1 ,2 ,34 ,6 ,7 ],100 ) def avg (scores,initial=0 ) : n=0 ;total=initial; for x in scores: total +=x n+=1 return (total,total/n) avg((1 ,2 ,34 ,6 ,7 )) avg([1 ,2 ,34 ,6 ,7 ],100 )
scope: del, global del強制變數gc global在函數內強制使用全域變數1 2 3 4 5 6 7 8 a=10 def foo (n) : global a a=100 return n+a foo(5 ),a
內建函式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 a=[0 ,1 ,2 ,3 ,4 ] len(a) sum(a) sum(a,1000 ) max(a),min(a) abs(3 ),abs(-3 ),abs(-3.14159 ) pow(2 ,5 ) pow(333 ,0 ),pow(0 ,0 ) pow(2 ,5 ,3 ) round(3.14159265358979323846 ,2 ) round(3.14159265358979323846 ) divmod(123 ,11 ) divmod(123.2389 ,11 ) all(([0 ,1 ],'aaa' ,True ,3 )) all(([],'' ,False ,0 )) all(([],'' ,False ,0 ,4 )) any(([0 ,1 ],'aaa' ,True ,3 )) any(([],'' ,False ,0 )) any(([],'' ,False ,0 ,4 )) a=1234 def f () :pass id(a) type(a),type(f) callable(a),callable(f) range(10 ) range(5 ,10 ) range(5 ,10 ,2 ) range(5 ,-12 ,-4 ) for i in range(len(a)): a[i]=a[i]+100 a a=3 print a,a,aa=raw_input() a
module 寫mymodule.py檔,其中可定義變數/函式1 2 3 4 5 6 7 import mymodule x=mymodule.functionA(1 ,2 ,3 ,4 ) y=mymodule.valueB `````` python import mymodule as mmx=mm.functionA(1 ,2 ,3 ,4 ) y=mm.valueB
1 2 3 from mymodule import * x=.functionA(1 ,2 ,3 ,4 ) y=valueB
1 2 3 from mymodule import functionA x=functionA(1 ,2 ,3 ,4 ) y=mymodule.valueB
standard module builtins dir(builtins ) keyword iskeyword math pi e log10 log sqrt sin ceil floor trunc … random seed random randint uniform shuffle choice … sys path maxint -sys.maxint-1
module name name future
python file name .py .py3 .pyc .pyo
file encoding -- encoding: utf-8 - - -- encoding: big5 - - -- encoding: ascii - - -- encoding: iso-8859-1 - -
as script file 1 2 3 chmod +x ./hello.py ./hello.py
List Comprehensions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 >>> S = [x**2 for x in range(10 )]>>> V = [2 **i for i in range(13 )]>>> M = [x for x in S if x % 2 == 0 ]>>> S;V;M;[0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 ] [1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 ] [0 , 4 , 16 , 36 , 64 ] >>> noprimes = [j for i in range(2 , 8 ) for j in range(i*2 , 50 , i)]>>> primes = [x for x in range(2 , 50 ) if x not in noprimes]>>> primes[2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 ] >>> words = 'The quick brown fox jumps over the lazy dog' .split()>>> words['The' , 'quick' , 'brown' , 'fox' , 'jumps' , 'over' , 'the' , 'lazy' , 'dog' ] >>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]>>> for i in stuff:... print i... ['THE' , 'the' , 3 ] ['QUICK' , 'quick' , 5 ] ['BROWN' , 'brown' , 5 ] ['FOX' , 'fox' , 3 ] ['JUMPS' , 'jumps' , 5 ] ['OVER' , 'over' , 4 ] ['THE' , 'the' , 3 ] ['LAZY' , 'lazy' , 4 ] ['DOG' , 'dog' , 3 ] >>> stuff = map(lambda w: [w.upper(), w.lower(), len(w)], words)>>> for i in stuff:... print i... ['THE' , 'the' , 3 ] ['QUICK' , 'quick' , 5 ] ['BROWN' , 'brown' , 5 ] ['FOX' , 'fox' , 3 ] ['JUMPS' , 'jumps' , 5 ] ['OVER' , 'over' , 4 ] ['THE' , 'the' , 3 ] ['LAZY' , 'lazy' , 4 ] ['DOG' , 'dog' , 3 ]
數值型別 0b1101,0xaa,0o1234 bin(100),hex(100),oct(100) 11111111111111111L #凡超過int最大值的數都自動轉成無窮精確度的long型別 1e6 314159e-5 314159E-5 float(‘nan’),float(‘inf’),float(‘-inf’) import math math.isnan(float(‘nan’)) math.isinf(float(‘inf’)) math.isfinite(float(‘inf’)),math.isfinite(float(‘nan’)) #only python3.x
三元運算 1 2 3 4 5 6 7 8 9 10 11 12 13 >>> x,y,z=1 ,2 ,3 >>> x if y>0 else z1 >>> (x>0 and x) or z 1 >>> d=100 ;n=None >>> a=d if n==None else n>>> b=(n==None ) and d or n>>> b1=(n==None and d) or n>>> b2= n==None and d or n>>> c=(n and d ) or n>>> a,b,b1,b2,c(100 , 100 , 100 , 100 , None )
operator from/to function 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 >>> list=[0 ,1 ,2 ]>>> list.__len__()3 >>> list.append(3 )>>> list[0 , 1 , 2 , 3 ] >>> x='good' ;y='bye' >>> x+y'goodbye' >>> x.__add__(y)'goodbye' >>> x=3 ;y=4 >>> x+y7 >>> x.__add__(y)7 >>> x.__add__(y).__sub__(y.__pow__(2 ))-9
type complex type(complex()) complex(1) complex(1,2) complex(1+2j,3+4j) complex(‘5-6j’) complex(‘5 - 6j’) #error complex()
z=4+5j;z z.real #實部 z.imag #虛部 z==z.real+z.imag*1j z.conjugate() #共軛複數
1 + - * / ** pow abs == !=
座標系轉換 1 2 3 4 5 6 7 8 import cmath abs(x) cmath.phase(x) ct=cmath.polar(x) cmath.rect(ct[0 ],ct[1 ]) cmath.sqrt(-1 ) import cmath exp log log10 acos asin acosh asinh ...
轉型
十進位 Decimal 1 2 3 4 5 6 7 from decimal import *Decimal Decimal(0.1 ), Decimal(3.14 ) Decimal('0.1' ), Decimal('3.14' ) D=Decimal a=D('2.33' );b=D('4.82' ) a+b
分數 Fraction 1 2 3 4 5 6 7 8 9 from fractions import *Fraction Fraction(1 ,3 ) F=Fraction F('-1/3' ) a,b,c=F('1/3' ),F('11/3' ),F('5/12' ) a+b,b-c,c*a,a/b abs(a-b),round(b) gcd(64 ,48 )
位元運算 ~ << >> & ^ | # callable() isinstance(x , types.FunctionType) isinstance(x, tuple) dir() dir(int) dir(list) a=3,list=[0,1,2,3] a.class , list__class type(a),type(list)
namespace local enclosing global builtin
Sized, Container, Sequence, MutableSequence, Iterable, Iterator 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 >>> list=[0 , 1 , 2 , 3 ]>>> lit=iter(list)>>> lit<listiterator object at 0x02ADD1D0 > >>> next(lit)0 >>> next(lit)1 >>> next(lit)2 >>> next(lit)3 >>> next(lit)Traceback (most recent call last): File "<stdin>" , line 1 , in <module> StopIteration
index, slice is, is not, ==, !=, in, not in, +, , +=, = len min max sum iter next slice range xrange reversed sorted zip enumerate index count append del extend insert pop reverse sort copy deepcopy # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 list=[33 ,44 ,55 ] itr=iter(list) while True : try : x=next(itr) print(x) except StopIteration: break n=0 for i in list: n+=i;i,n n=0 for i in iter(list): n+=i;i,n n=0 for i in range(1 ,10 +1 ): n+=i;i,n n=0 for i,v in enumerate(list): i,v ii=[3 ,2 ,1 ] for i,v in zip(ii,list): i,v data=zip(ii,list) sorted(data) data def k (x) :return x[1 ];sorted(data,key=k)
list comprehension 1 2 3 4 5 6 7 8 list=[0 ,1 ,2 ,3 ,4 ,5 ] [x*x for x in list] [str(x)+'*' +str(y)+'=' +str(x*y) for x in range(2 ,9 +1 ) for y in range(1 ,9 +1 )] li0=['a' ,'b' ,'c' ] li1=['.jpg' ,'.png' ,'.bmp' ] [x+y for x in li0 if x!='a' for y in li1 if y!='.jpg' ]
string \’ \” \ \n \r \t #HT; tab \v #VT \a #bell \b #backspace \f #page \xff #hex \ooo #oct
‘’’附號用來合併多行 s=’’’abc def ghi kkl mno pqr\t\nstu vwxyz’’’ s
raw r或R都可以 r’\‘ R’\‘ r’\”‘ R’\”‘
\標示下一行繼續 s=’abc\ def\ hij’ s
dict 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 d={} d={'name' :'John' ,'name' :27 } d={'name' :'John' ,'age' :27 ,'list' :[3 ,4 ,5 ]} d['name' ] type(d) dict(d) type(dict(d)) keys=['name' ,'age' ,'job' ] values=['john' ,33 ,'programmer' ] d2=dict(zip(keys,values));d2 d={'a' :1 ,'b' :2 ,'c' :3 } for k in d: k for k in d.keys(): k for v in d.values(): v for k,v in d.items(): k,v
len del get setdefault keys values items
set 1 2 3 4 x={1 ,2 ,3 ,4 ,4 ,4 ,4 };x set(x); set({1 ,2 ,3234 ,234 ,1 ,1 ,1 ,1 }) set([2 ,3 ,2 ,2 ,2 ,2 ,2 ])