程序塊與做用域python
#!/usr/bin/env python ## 腳本設置env啓動,env能夠在系統的PATH查找
# -*- coding: UTF-8 -*- ## 設置當前python的字符編碼
def fn():
print("python3.0") ## python3.0 的打印輸出
print "python2.7" ## python2.7 的打印輸出複製代碼
每一個使用冒號":"標記的程序塊內的代碼必須有相同的描述python3.x
判斷語句app
a = 9
b = 4
c = None
## 第一種形式
if not c: ## c不是None的時候執行if下的語句
pass ## 表示須要寫代碼可是實際什麼也不作的場合
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複製代碼
循環語句python2.7
## 基本格式
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 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) ## 將三個變量名設置爲整數0、一、2
## python3.x擴展序列解包
>>> 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]複製代碼
總結:python3.x帶"*"老是向其賦值一個列表,即便是匹配單個項,若是沒有匹配會返回一個空的列表工具
表達式語句編碼
## 經常使用表達式
fn(args) ## 函數調用
obj.call(args) ## 對象方法調用
spam ## 交互模式下打印變量
print(str) ## python3.x打印操做
yiled x ** 2 ## 產生表達式語句
## 使用函數表達式並改變值
>>> L = [1,2,3]
>>> L.append(4)
>>> L
1,2,3,4
## python3.x之print函數打印格式
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout][, flush=False])
sep:是在每一個對象之間插入
end:在文本打印以後追加end的字符串信息
file:將信息輸出到指定的終端,默認是sys.stdout,即控制檯
flush:py3.3新增特性,即設置爲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函數,導入如下包
from __future__ import print_function複製代碼
迭代器spa
若是對象是實際保存的序列,或者能夠在迭代工具中for一次產生一個結果的對象則稱爲可迭代 code
## 基本迭代器
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='')
## 手動設置迭代器iter和next
L = [1, 2, 3]
I = iter(L)
while True:
try:
X = next(I)
except StopItration:
break
print(X ** 2,end=' ')
## 內建迭代器類型,字典
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")]
## 擴展的列表解析
lines = [line for line in open("data.txt") if line[0] == "k"] ## for循環下帶有if語句塊
list = [x + y for x in range(10) for y in range(5)] ## for循環嵌套for循環複製代碼
python3.x新增迭代器對象
## range迭代器
>>> R = range(10)
>>> I = iter(R)
>>> next(I) ## 每次調用next就會輸出列表的下一個元素
## map迭代器:map(func, *iterables):接受一個函數和一個迭代器對象,將全部的迭代器對象通過函數處理獲得一個新的迭代對象數據
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):第一個參數必填,接受能夠迭代的對象,並將每組對象的對應元素從新組成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):接受一個函數和一個迭代對象,將符合函數filter_fn要求的將返回迭代數據
list(filter(bool, ['spam', '', 'ni'])) < = > [x for x in ['spam', '', 'ni'] if bool(x)]複製代碼