python語句語法
程序塊與作用域
- 相同縮進(jìn)范圍的代碼在一個程序塊和作用域中
- 同一個程序塊和作用域中不能有不同的縮進(jìn)
#!/usr/bin/env python ## 腳本設(shè)置env啟動,env可以在系統(tǒng)的PATH查找
# -*- coding: UTF-8 -*- ## 設(shè)置當(dāng)前python的字符編碼
def fn():
print("python3.0") ## python3.0 的打印輸出
print "python2.7" ## python2.7 的打印輸出
每個使用冒號":"標(biāo)記的程序塊內(nèi)的代碼必須有相同的描述
判斷語句
a = 9
b = 4
c = None
## 第一種形式
if not c: ## c不是None的時候執(zhí)行if下的語句
pass ## 表示需要寫代碼但是實(shí)際什么也不做的場合
if a > b:
pass
if c is None:
pass
## 第二種形式
if a > b:
print("a > b") ## python3.x的打印
else:
print("a <= b")
## 第三種形式
if a >= 10:
print("a > 10")
elif 5 < a < 10: ## ==> a > 5 and a < 10
print("5 < a < 10")
else:
print("a <= 5")
## 第四種形式
a = 9
b = 2
num = a if a > 10 else b ##num is b
循環(huán)語句
- while 循環(huán)
## 基本格式
while test:
statement1
else:
statement2
## 例子
children = ["tom","keithl","jane","mani","bob"]
while len(children) > 0:
print "pop the child[%s]" % children.pop()
else:
print("there have not any ele in chidlren ...")
pop the child[bob]
pop the child[mani]
pop the child[jane]
pop the child[keithl]
pop the child[tom]
- for 循環(huán)
## 基本格式
for target in object:
statements
else:
statements
## 示例
>>> for x in ["spam", "eggs", "ham"]:
... print(x, end=' ')
...
spam eggs ham
## 遍歷帶有元組信息的列表
>>> T = [(1, 2), (3, 4), (5, 6)]
>>> for (a, b) in T: # Tuple assignment at work
... print(a,b)
...
1 2
3 4
5 6
## 遍歷字典
D = {'a': 1, 'b': 2, 'c': 3}
## 遍歷字典方法1
for key in D:
print(key, '=>', D[key])
## 遍歷字典方法2
for (key, value) in D.items():
print(key, '=>', value)
## 使用python3.x遍歷并序列解壓
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
print(a, b, c)
賦值語句
- 序列賦值語句
## 基本賦值
>>> num = 1
>>> wind = 9
>>> A,B = num,wind
>>> A,B
(1,9)
## 高級賦值
>>> str = "ABCD"
>>> a,b,c = str[0],str[1],str[2]
>>> a,b,c = list(str[:2]) + [str[2:]]
>>>(a,b),c = str[:2],str[2:]
>>> a,b,c = range(3) ## 將三個變量名設(shè)置為整數(shù)0烟央、1堂飞、2
## python3.x擴(kuò)展序列解包
>>> seq = [1,2,3,4]
>>> a,*b = seq
>>> a
1
>>> b
[2,3,4]
>>> *a,b = seq
>>> a
[1,2,3]
>>> b
[4]
>>> a,*b,c = seq
>>> a
1
>>> b
[2,3]
>>> c
4
>>> a,b,*c = seq
>>> a
1
>>> b
2
>>> c
[3,4]
總結(jié):python3.x帶""總是向其賦值一個列表西傀,即使是匹配單個項(xiàng),如果沒有匹配會返回一個空的列表*
表達(dá)式語句
## 常用表達(dá)式
fn(args) ## 函數(shù)調(diào)用
obj.call(args) ## 對象方法調(diào)用
spam ## 交互模式下打印變量
print(str) ## python3.x打印操作
yiled x ** 2 ## 產(chǎn)生表達(dá)式語句
## 使用函數(shù)表達(dá)式并改變值
>>> L = [1,2,3]
>>> L.append(4)
>>> L
1,2,3,4
## python3.x之print函數(shù)打印格式
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout][, flush=False])
sep:是在每個對象之間插入
end:在文本打印之后追加end的字符串信息
file:將信息輸出到指定的終端,默認(rèn)是sys.stdout,即控制臺
flush:py3.3新增特性,即設(shè)置為True時立即將信息刷新到輸出流的目的終端上而無須等待
## 示例
>>> print(x, y, z, sep=', ')
spam, 99, ['eggs']
## 將信息輸出到data.txt中
>>> print(x, y, z, sep='...', file=open('data.txt', 'w'))
## 兼容python2.x和python3.x的print函數(shù)普筹,導(dǎo)入以下包
from __future__ import print_function
迭代器
如果對象是實(shí)際保存的序列,或者可以在迭代工具中for一次產(chǎn)生一個結(jié)果的對象則稱為可迭代
## 基本迭代器
for x in [1, 2, 3, 4]:
print(x ** 2, end=' ')
## 文件迭代器
## 第一種方式
for line in open('script2.py'):
print(line.upper(), end='')
## 第二種方式
for line in open('script2.py').readlines():
print(line.upper(), end='')
## 第三種方式
f = open('script2.py')
while True:
line = f.readline()
if not line: break
print(line.upper(), end='')
## 手動設(shè)置迭代器iter和next
L = [1, 2, 3]
I = iter(L)
while True:
try:
X = next(I)
except StopItration:
break
print(X ** 2,end=' ')
## 內(nèi)建迭代器類型隘马,字典
D = {'a':1, 'b':2, 'c':3}
for key in D.keys():
print(key, D[key])
## 列表解析
x = [y + 10 for y in range(10)]
## 文件列表解析
lines = [line for line in open("data.txt")]
## 擴(kuò)展的列表解析
lines = [line for line in open("data.txt") if line[0] == "k"] ## for循環(huán)下帶有if語句塊
list = [x + y for x in range(10) for y in range(5)] ## for循環(huán)嵌套for循環(huán)
python3.x新增迭代器
## range迭代器
>>> R = range(10)
>>> I = iter(R)
>>> next(I) ## 每次調(diào)用next就會輸出列表的下一個元素
## map迭代器:map(func, *iterables):接受一個函數(shù)和一個迭代器對象太防,將所有的迭代器對象經(jīng)過函數(shù)處理得到一個新的迭代對象數(shù)據(jù)
num = map(abs,(-2,-3,-5,9,3))
for n in num:
print(n,end=",")
2,3,5,9,3,
## zip迭代器:zip(iter1, iter2=None, *some):第一個參數(shù)必填酸员,接受可以迭代的對象蜒车,并將每組對象的對應(yīng)元素重新組成tuple
z = zip((1,2,3),(5,6,7))
for pair in z:
print(pair)
(1, 5),(2, 6),(3, 7),
## filter迭代器:filter(filter_fn,*iterables):接受一個函數(shù)和一個迭代對象,將符合函數(shù)filter_fn要求的將返回迭代數(shù)據(jù)
list(filter(bool, ['spam', '', 'ni'])) < = > [x for x in ['spam', '', 'ni'] if bool(x)]