一.赋值
1.序列解包
多个赋值可以同时操作
x ,y ,z = 1,2,3
print x,y,z
--->1,2,3
#两元素之间的互换也可以
x,y = y,x
print x,y,z
--->2,1,3
将多个值得序列解开,然后放到变量的序列中,等同于下面的代码
>>> values = 1,2,3
>>> values
(1, 2, 3) >>> x,y,z = values >>> x 1
序列解包中的元素数量必须和等号左边的变量数完全一致,否则会报错
>>> x,y = 1,2,3
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module> x,y = 1,2,3 ValueError: too many values to unpack
二. 条件和条件语句
Boolean 值 ---True False
Fasle None 0 "" [] () {} ---为 False 其他都未 True
bool 函数可以用来住转化其他值
>>> bool('this is a ')
True
>>> bool(1) True >>> bool(0) False >>> bool() False
条件执行和 if,esle,elif 语句
num = int(input('enter the number:'))
if num > 0: print 'the number is > 0' elif num < 0: print 'the number is < 0' else: print 'the number is = 0'
嵌套的代码块
name = raw_input("pls enter the name:")
if name.endswith('z'): if name.startswith('m'): print 'hello m' elif name.startswith('l'): print 'hello l' else: print'z' else: print 'hello stranger'
比较运算符
"==" , "is" ,"is not", "in", "not in" .......(> <)
逻辑运算符
"and" ,"or","not"
断言
类似于 要求某些条件必须为真,否则 .....
if not condition:
crash program
>>> age = 10
>>> assert 0< age <100
>>> age = -1
>>> assert 0 < age < 10
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
assert 0 < age < 10
AssertionError
三. 循环
1.while 循环 --任何情况为真的条件下重复执行一块代码
>>> x = 1
>>> while x < 100:
print x x += 1
------》 1~99
2.for 循环 --要为一个集合(序列 或其他可迭代的对象)的每一个元素都执行一块代码
>>> words = ['this','is','a','boy']
>>> for word in words: print word >>> nums = [1,2,3,4,5,6,7,8,9] >>> for num in nums: print num
3.循环遍历字典
>>> d ={'x' :1,'y':2,'z':3}
>>> for key in d: print key + ":" ,d[key]
4.并行迭代
>>> names = ['zhang','cheng','ni']
>>> ages = [20,21,22] >>> for i in range(len(names)): print names[i],'is',ages[i] zhang is 20 cheng is 21 ni is 22
zip() -- 把两个序列"压缩"在一起,然后返回一个元祖的列表 (可以用于任意多的序列,可以应付不等长度的序列,以最短的序列为准)
>>> zip(names,ages)
[('zhang', 20), ('cheng', 21), ('ni', 22)]
[('zhang', 20), ('cheng', 21), ('ni', 22)]
>>> for name,age in zip(names,ages):
print name ," is" ,age ," old"
zhang is 20 old
cheng is 21 old
ni is 22 old
enumerate() -- 在提供索引的地方迭代索引-值对
>>> strings = ['ni','hao','wa','wo']
>>> for index,string in enumerate(strings): print index,'',string 0 ni 1 hao 2 wa 3 wo
5.跳出循环
break --跳出并停止循环
continue --跳出该次循环,并不停止循环
6.循环中的else语句 --循环中没有调用break 的情况下
from math import sqrt
for n in range(99,81,-1): root = sqrt(n) if root == int(root): print n break else: print "Dont't find it"
6.列表推导式 --利用其它列表创建新列表
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x*x for x in range(10) if x %3 ==0] [0, 9, 36, 81] >>> [(x,y) for x in range(10) for y in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (6, 2), (7, 0), (7, 1), (7, 2), (8, 0), (8, 1), (8, 2), (9, 0), (9, 1), (9, 2)]