import somemodule
或者
from somemodule import somefunction
或者
from somemodule import somefunction , anotherfunction,yetanotherfunction
或者
form somemodule import *
給導入模塊取別名
import somemodule as xxxxmodule
from somemodule import somefunction as xxxfunction
eg.
>>> import math as testmodule
>>> testmodule.sqrt(9)
3.0
>>> from math import sqrt as test
>>> test(9)
3.0
2.賦值魔法
序列解包(sequence unpacking)
交換
eg.
>>> x,y,z = 1,2,3
>>> x,y,z
(1, 2, 3)
>>> x,y,z = z,x,y
>>> x,y,z
(3, 1, 2)
元組賦值
>>> myinfo
{'tel': '18081953671', 'name': 'Bruce'}
>>> key,value=myinfo.popitem()
>>> key,value
('name', 'Bruce')
3.0版本中有一個特殊用法
a,b,rest*=[1,2,3,4,5,6],賦值結果a=1,b=2,剩余的值收集道rest中
鏈式賦值
x=y=somefunction()
等效于
y=somefunction()
x=y
增量賦值
x=6
x += 2? x -= 3 x *= 4
對其他數(shù)據(jù)類型同樣適用
>>> x = 'bruce'
>>> x += ' study'
>>> x
'bruce study'
>>> x *= 2
>>> x
'bruce studybruce study'
3.條件和條件語句
bool類型
>>> True
True
>>> False
False
>>> True==1
True
>>> False==0
True
bool函數(shù)
>>> bool('Bruce study python')
True
>>> bool(20)
True
>>> bool('')
False
>>> bool(0)
False
條件執(zhí)行 if elif else
if 條件:
? ? ? 語句1
? ? ? 語句2
? ? ? ....
elif:
? ? ? 語句1
? ? ? 語句2
? ? ? ....
else:
? ? ? 語句1
? ? ? 語句2
? ? ? ....
于其他語言不同的比較
x is y? ? x和y是同一個對象?
x is not y x和y是不同的對象?
x in y y是x容器
x not in y y不是x容器
== 和 is的區(qū)別:==比較兩個對象是否相等踪区,is 比較兩個對象是否是同一個對象
>>> m=[1,2]
>>> n=[1,4]
>>> m==n
False
>>> m is n
False
>>>n[1]=2
>>>m=n
>>>True
>>>m is n
>>>False
in 成員運算符
字符串和序列比較
bool運算符
斷言assert
4.循環(huán)
while循環(huán)
x=1
while x<=100
print x
x +=1
for循環(huán)
for a in b
? xxxx
? xxxx
迭代工具
zip函數(shù)
>>> name=['nancy','bruce','pipi','popo']
>>> age=[28,34,2,61]
>>> zip(name,age)
[('nancy', 28), ('bruce', 34), ('pipi', 2), ('popo', 61)]
enumerate函數(shù)
翻轉和排序迭代
>>> a=[2,3,7,2,3,9,5]
>>> sorted(a)
[2, 2, 3, 3, 5, 7, 9]
>>> list(reversed(a))
[5, 9, 3, 2, 7, 3, 2]
注意驱入,sorted函數(shù)并沒有改變a這個列表赤炒,reversed函數(shù)也沒有改變a列表本身
循環(huán)跳出
break語句 continue語句
for x in seq:
? if condition1:continue
? if condition1:continue
? if condition1:continue
? do_something()
? .....
? .....
自己寫的簡單程序
while True:
if name != 'Bruce':
? name = raw_input('input your name:')
else:
? if password != '123456':
? password = raw_input('input your password:')
? else:
? print 'you have input the right name and password!'
? name=password=''?
? continue
if name == 'over':
? break
列表推倒式
利用其他列表創(chuàng)建薪列表的一種方法
pass,del,exec語句
pass 什么都不做 跟nop類似氯析,作用是當部分代碼未完成而需要代碼來填充格式
del 刪除那些不再使用的對象
exec和eval
書上說這兩個函數(shù)要慎用
小結:
1.打印
2.導入
3.賦值
4.塊
5.條件
6.斷言
7.循環(huán)
8.列表推倒式
9.pass del exec eval語句