@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 | % 除法只取餘數 |
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
a=b=c=3
b=4;c=5
x=y=z=[0,1,2,3,4]
x,y,z #自動組成tuple
serial assignment
(a,b,c)=(0,1,2)
a;b;c;
a,b,c=0,1,2
a,b=b,a #exchange a,b
a;b;c;
[a,b,c]=[9,8,7] #list或tuple寫法都可以
a;b;c;
star mark for only python3
x=[0,1,2,3,4,5]
a,*b,c=x
a,b,c #等於(0,[1,2,3,4],5)
+= -= = /= %= //= *= >>= <<= &= ^= |=
if/elif/else 使用:和tab做區塊包圍檢查
1 | a,b,c=1,2,3 |
1 | a,b,c=0,'',[] |
while
1 | i=1;x=0; |
for
1 | scores=[23,54,52,55,99] |
for char in str
1 | s='hello world' |
serial assignment for list/tuple in for
1 | nameScores=(('banana',32,55),('apple',67,48),('orange',72,8)) #list/tuple都可以 |
break/continue for while/for
function; def/return
1 | def testfunction(param): |
1 | def sum(numbers,initial): |
scope: del, global
del強制變數gc
global在函數內強制使用全域變數1
2
3
4
5
6
7
8a=10 #什麼數值都無所謂
#del a #讓a變成未定義也不影響後面的global操作
def foo(n):
global a
a=100
return n+a
foo(5),a #105,100
內建函式
1 | a=[0,1,2,3,4] |
module
寫mymodule.py檔,其中可定義變數/函式1
2
3
4
5
6
7import mymodule #這就可以引入mymodule.py裡定義的一切
x=mymodule.functionA(1,2,3,4)
y=mymodule.valueB
`````` bash
import mymodule as mm#這就可以引入mymodule.py裡定義的一切, module name改用alias name使用
x=mm.functionA(1,2,3,4)
y=mm.valueB
1 | from mymodule import * #引入一切,使用時不需要加上mymodule. |
1 | from mymodule import functionA #引入一切,使用時只有指定的import功能不需要加上mymodule. |
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
!/usr/bin/python
chmod +x ./hello.py
./hello.py
List Comprehensions
1 | >>> S = [x**2 for x in range(10)] |
數值型別
#
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
三元運算
x,y,z=1,2,3
x if y>0 else z
1
(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
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+y
7
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() #共軛複數
+ - / * pow abs == !=
座標系轉換
import cmath
abs(x) #絕對值;模
cmath.phase(x) #輻角;弧度
ct=cmath.polar(x) #模和輻角的tuple
cmath.rect(ct[0],ct[1]) #以模和輻角建立complex
cmath.sqrt(-1) #負數的平方根
#
import cmath
exp log log10 acos asin acosh asinh …
轉型
str()
repr()
十進位 Decimal
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
from fractions import
Fraction
Fraction(1,3) #1/3
F=Fraction
F(‘-1/3’)
a,b,c=F(‘1/3’),F(‘11/3’),F(‘5/12’)
a+b,b-c,ca,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
list=[0, 1, 2, 3]
lit=iter(list)
lit
next(lit)
0
next(lit)
1
next(lit)
2
next(lit)
3
next(lit)
Traceback (most recent call last):
File ““, line 1, in
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
#
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
list=[0,1,2,3,4,5]
[x*x for x in list]
[str(x)+’‘+str(y)+’=’+str(xy) 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
d={}
d={‘name’:’John’,’name’:27} #同key會被取代
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
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])