if 测试的语法结构
if boolean_expression1:
suite1
elif boolean_expression2:
suite2
…
else:
else_suite
elif语句是可选的
仅用于占位,而后再填充相关语句时,可以使用pass
if/else三元表达式
通常在为某变量设定默认值时通常用到的如下格式
if x:
a=y
else:
a=z
可以改写为如下简短格式
a = y if x else z
其通用条件表达式语法格式为
expression1 if boolean_expression else expression2
如果boolean_expression的值为True,则条件表达式的结果为expression1,否则为expression2
while 循环
用于编写通用迭代结构
顶端测试为真即会执行循环体,并会重复多次测试直到为假后执行循环后的其他语句
for 循环
一个通用的序列迭代器,用于遍历任何有序的序列对象内的元素
可用于字符串、元组、列表和其它的内置可迭代对象,以及通过类所创建的新对象
python也提供了一些能够进行隐性迭代的工具
in成员关系测试
列表解析
map、reduce和filter函数
while 循环
语法格式
while boolean_expression:
while…suite
else:
else…suite
else分支为可选部分
只要boolean_expression的结果为True,循环就回执行;
boolean_expression的结果为False时终止循环,此时如果有else分支,则会执行
url = ‘www.magedu.com'
while url:
print url
url = url[:-1]
else:
print “game over”
输出结果为:
www.magedu.com
www.magedu.co
www.magedu.c
www.magedu.
www.magedu
www.maged
www.mage
www.mag
www.ma
www.m
www.
www
ww
w
game over
url = ‘www.magedu.com'
while url:
print url
url = url[:-1]
x +=1
if x >7:
break
else:
print “game over”
输出结果为:
www.magedu.com
www.magedu.co
www.magedu.c
www.magedu.
www.magedu
www.maged
www.mage
while:
while bool_expression:
while_suite
else:
else_suite
break:跳出最内层的循环:
continue:跳到所处的最近层循环的开始处:
pass:点位语句
else代码块:循环正常终止才会执行:如果循环终止是由break跳出导致的,则else不会执行:
练习题:
练习1:逐一显示指定列表中的所有元素:
代码如下:
l1 = [1,2,3,4,5,6]
while l1:
print l1.pop(0),
运行结果:1 2 3 4 5 6
l2 = ['abc','bcd','cde']
count = 0
while count <len(l2):
print l2[count]
count +=1
while l2:
print l2[0]
l2=l2[1:]
练习2:求100以内所有偶数之和:
代码如下:
i = 1;sum = 0
while i<=100:
if i%2==0:
sum += i
i += 2
else:
i +=1
print sum
运行结果:2550
i = 0;sum = 0
while i<=100:
if i%2==0:
sum += i
i += 2
print sum
运行结果:2550
扩展题:求num以内所有奇数之和:
num = int(raw_input('请输入一个num:'))
i = 1;sum =0
while i<=num:
if i%2!=0:
sum += i
i += 2
else:
i +=1
print sum
运行结果:2500
练习3:逐一显示指定字典的所有建:并显示结束后说明总键数:
运行代码:
d1 = {'xiaohao':78,'xiaoming':89,'wangwu':100}
count = 0
x = d1.keys()
while count <len(x):
print x[count]
count +=1
print count
运行结果:
xiaohao
xiaoming
wangwu
3
练习4:创建一个包含了100以内所有奇数的列表:
运行代码:
i = 1;sum = 0
while i<=100:
if i%2!=0:
sum += i
i +=2
else:
i +=1
print sum
运行结果;2500
练习5:逆序逐一显示一个列表的所有元素
运行代码:
l1 = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
i = 0
while i<len(l1):
l1.reverse()
print l1[i]
i +=1
运行结果:
Sun
Tue
Fri
Thu
Wed
Sat
Mon
练习6:列表l1=[0,1,2,3,4,5,6],列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],以第一个列表中的元素为键,以第二个列表中的元素为值生成字典d1:
运行代码:
l1=[0,1,2,3,4,5,6]
l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
d1= {}
count = 0
if len(l1)==len(l2):
while count <len(l1):
d1[l1[count]]=l2[count]
count +=1
print d1
运行结果:
{0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'}
死循环
while True:
for 循环
语法格式
for expression1 in iterable:
for_suite
else:
else_suite
通常,expression或是一个单独的变量,或是一个变量序列,一般以元组的形式给出
如果以元组或列表用于expression,则其中的每个数据项都会拆分到表达式的项,例如
T=[(1,2),(3,4),(5,6),(7,8)]
for (a,b) in T
print a b
for i in range(1,101):
sum +=i
print sum
for i in xrange(1,101):
sum +=i
for 循环形式扩展
语法格式
for expression in iterable:
for_suite
if boolean_expression2:break
if boolean_expression3:continue
else:
else_suite
编写循环的技巧
for 循环比while循环执行速度快
python提供了两个内置函数,用于在for循环中定制特殊的循环
range或xrange
range:一次性地返回连续地整数列表
xrange:一次产生一个数据元素,相较于range更节约空间
range函数
非完备遍历
用于每隔一定的个数元素挑选一个元素
S = ‘How are you these days?’
range(0,len(S),2)
>> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
for i in range(0,len(S),2):print S[i],
>>H w a e y u t e e d y ?
修改列表
L = [1,2,3,4,5]
for i in range(len(L)):L[i]+=1
L
>>[2,3,4,5,6]
zip
返回并行地元素元组的列表,常用于在for循环中遍历数个序列
取得一个或多个序列为参数,将给定序列中的并排的元素配成元组,返回这些元组的列表
当参数长度不同时,zip会以最短序列的长度为准
可在for循环中用于实现并行迭代
l1 = [1,2,3,4,5,6,7]
l2 = ['a','b','c','d','e','f','g']
zip(l1,l2)
运行结果:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g')]
zip也常用于动态构造字典
keys = [1,2,3,4,5,6,7]
values = ['Mon','Tus','Wed','Thu','Fri','Sat','Sun']
D={}
for (k,v) in zip(keys,values): D[k] = v
print D
运行结果:
{1: 'Mon', 2: 'Tus', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat', 7: 'Sun'}
for 循环练习:
练习1:逐一分开显示指定字典d1中的所有元素,类似如下
代码如下:
d1 = {‘a’:12,’b’:23,’c’:34}
for (k,v) in d1.items():print k,v
运行结果:
>>
a 12
c 34
b 23
练习2:逐一显示列表中l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]中的索引为奇数的元素:
l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
i = 1
for i in range(1,len(l1),2)
print l1[i],
运行结果:
>> Mon Wed Fri
练习3:将属于列表l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],但不属于列表l2=["Sun","Mon","Tue","Wed","Thu"]的所有元素定义为一个新列表l3;
代码如下:
l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
l2=["Sun","Mon","Tue","Wed","Thu"]
l3 = []
for i in l1:
if i not i l2:
l3.append(i)
print l3
运行结果:
['Fri', 'Sat']
练习4:已知列表namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'],删除列表removelist=['stu3','stu7','stu9']:请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可):
代码如下:
namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7']
removelist=['stu3','stu7','stu9']
for i in removelist:
if i in namelist:
namelist.remove(i)
print namelist
运行结果:
['stu1', 'stu2', 'stu4', 'stu5', 'stu6']
回顾:
1 动态语言
sys.getrefcount()
增加对象的引用计数场景:
对象创建时
将对象添加到容器时;类似list.append()
当对象被当作参数传递给函数时
为对象创建另外变量名
减少引用计数:
引用此对象的某变量名被显式销毁: del x
给引用此对象的某变量名重新赋值
从容器中移除对象时,类似list.pop()
容器本身被销毁
2 if
if boolean_expression:
...
elif bool_expression:
...
else:
...
3 while
while bool_expression:
while_suite
if bool_expression2:continue
if bool_expression3:break
else:
else_suite
4 for
for expression in object:
for_suite
if bool_expression2:continue
if bool_expression3:break
else:
else_suite