Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12768
  • 博文数量: 5
  • 博客积分: 240
  • 博客等级: 二等列兵
  • 技术积分: 75
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-02 16:45
文章分类

全部博文(5)

文章存档

2012年(5)

我的朋友

分类: Python/Ruby

2012-08-14 15:14:29

5条件、循环和其他语句
5.1 print 和 import的更多信息
5.11 使用逗号输出
用,分隔可打印多个表达式
eg: print 'Age:' , 60 #Age:60
同时输出文本和变量值,又不希望使用字符串格式化
eg: greeting='Hello!'
title='Dr.'
name='Alice'
print greeting,title,name #Hello! Dr. Alice
print 'Hello',',','World' #Hello , World
print 'Hello' + ',' + 'World' #Hello,World
print 'Hello',
print 'World' #Hello World
5.12 把某件事作为另一件事导入
从模块导入函数 import module
from module import function
from module import function,anotherfunction,yetanotherfunction
from module import * #从给定的模块导入所有函数
如果2个模块有同样的函数名,如何调用
import module1
import module2
module1.function(...)
module2.function(...)
或者:
import module as XXX
XXX.function(...)
或者
from module import function as XXX
XXX(...)

5.2 赋值魔法
5.21 序列解包
多个赋值操作可以同时进行
eg: x,y,z=1,2,3
print x,y,z #1 2 3
x,y=y,x #序列解包,将多个值的序列解开,再放到变量的序列中
print x,y,z #2,1,3
当函数返回元组或其他序列或可迭代对象时,这个特性尤其有用。假设需要获取(删除)字典中任意的项时,可以用popitem,会将项作为元组返回,这个元组就可以直接赋值到两个变量中,它允许函数返回一个以上的值并打包成元组,然后通过赋值语句访问,但解包的序列元素量必须与变量数量一致
5.22 链式赋值
将同一个值赋给多个变量的捷径,详见‘同一性运算符’
eg: x=y=function() #与此相同: y=function();x=y
5.23 增量赋值
将表达式运算符放在赋值运算符左边,对于+-/*等标准运算符都适用
eg: x=2
x+=1 #x=x+1;3
x*=2
print x #x=x*2;6

5.3 语句块:缩排的乐趣
语句块是在条件为真时执行或者执行多次(循环)的一组语句,在代码前放置空格来缩进语句即可创建语句块。
块中的每行应该缩进相同的量
用:标示语句块的开始

5.4 条件和条件语句
5.41 布尔变量的作用
False、None、0、""、()、[]、{} 在作为布尔表达式时,会被解释器看做假(即标准值False,None,所有类型的数字0,空序列,空字典)
其他值都能被解释成真
5.42 条件执行和if语句
eg: name=raw_input('what\'s you name?')
if name.endswith('Alice'):print 'Hello, Alice!'
5.43 else子句
eg: name=raw_input('what\'s you name?')
if name.endswith('Alice'):
print 'Hello, Alice!'
else: 
print 'Hello, stranger!'
5.44 elif子句
检查多个条件
eg: num=input('please enter a number') #可以用int(raw_input(...))代替input
if num > 0 :
print 'the number is positive'
elif num == 0 :
print 'the number is zero'
else :
print 'the number is negative'
5.45 嵌套代码块
eg: name=raw_input('what\'s you name?')
if name.endswith('Gates'):
if name.startswith('Mr.'):
print 'Hello,Mr.Gates'
elif name.startswith('Mrs.'):
print 'Hello,Mrs.Gates'
else:
print 'Hello,Gates'
else: print 'Hello stranger!'
5.46 更复杂的条件
在python中比较运算和赋值运算一样是可以连接的,eg: 0
1.比较运算符
x==y
x
x>y
x>=y
x<=y
x!=y
x is y x和y是同一个对象
x is not y
x in y x是y的成员
x not in y
2.相等运算符==
单个相等运算符是赋值运算符,用来改变值,不能用来比较
3.is:同一性运算符
eg: x = y = [1,2,3]
z = [1,2,3]
if x==y:print 'x is', x
if x==z:print 'z is',z
if x is y: print 'x is y'
else:print 'x is not y'
if x is z:print 'x is z'
else: print 'x is not z' #x is y,x is not z
is运算符判定同一性而不是相等性,xy都绑定在同一个列表上,而z绑定在另一个列表上,只不过列表的值和顺序相同,故对象不同
eg: x=[1,2,3]
y=[2,4]
if x is y: print 'x is y'
else:print 'x is not y' #x is not y
del x[2] #x=[1,2]
y[1]=1 #y=[2,1]
y.reverse #y=[1,2]
if x is y: print 'x is y'
else:print 'x is not y' #x is not y
4.in:成员资格运算符
eg: name=raw_input('name?\n')
if 'A' in name:
print 'your name contain letter "A".'
else:
print 'your name does notcontain letter "A".'
5.字符串和序列比较
'alpha' < 'beta' #True
'abc' < 'abcd' #True
'abc' < 'ABC' #False
[1,2] < [2,1] #True
6.布尔运算符
and、or、not逻辑运算符即布尔运算符
eg: if num <=10 and num >=1: #也可写成:1<=num<=10
print 'your nunber is right'
else:
print 'your number is not in 1-10'
python2.5有个内置表达式:a if b else c,即如果b为真返回a,否则返回c
print 'wrong' if num <1 else 'ok' #如果输入的数字小于1,打印wrong,否则打印ok
5.47 断言
伪代码:if condition: crash program
assert可以作为程序的检查点
eg: num=input('please enter a number between 1 and 10\n')
assert 1 < num < 10,'the num must be in 1-10' #如果输入不在区间内,会返回错误:the num must be in 1-10,错误信息可自定义

5.5 循环
5.51 while循环
任何条件为真的情况下重复执行一个代码块
eg: x=1
while x <=100:
print x
x+=1 #自动打印1-100
5.52 for循环
为一个集合(序列或者其他可迭代对象)的每个元素都执行一个代码块
eg: num=[1,2,3,4,5] #也可以用num=range(1,6);python里范围指定都是含前不含后的
for i in num:
print i #打印1-5
5.53 循环遍历字典元素
for语句能循环遍历字典的所有键
eg: d={1,2,3,4}
for key in d:
print key
5,54 一些迭代工具
1.并行迭代
eg: name=['shanghai','beijing','guangzhou']
num=['021','010','020'] #必须要加引号,否则会认为是八进制
for i in range(len(name)): #len返回name的个数=range(3),range如果只提供上限,默认下限为0
print name[i],'is',num[i]
zip函数:把序列压缩在一起,返回一个元组
eg: print zip(name,num) #[('shanghai', '021'), ('beijing', '010'), ('guangzhou', '020')]
在循环中解包元组
eg: for name,num in zip(name,num):
print name,'\'s code is:',num

zip可以应付不等长序列:当最短序列用完,就会停止
eg: print zip(range(5),xrange(1000000)) #[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)],xrange需要迭代巨大序列时比range高效,此处不推荐用range替换xrange,尽管只需要前5个数,但是range会计算所有数字
2.编号迭代
在想要迭代序列中的对象同时,还要获取对象的索引
enumerate:在提供索引的地方迭代索引-值对
eg: for index,string in enumerate(strings):
if 'xxx' in string:
strings[index]='[consored]'
3.翻转和排序迭代
sorted、reversed
eg: print sorted('Hello,world') #[',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
list(reversed('hello,world')) #[' ', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
5.5 跳出循环
1.break
结束循环:break
eg: from math import sqrt
for n in range(99,0,-1): #-1表示步长,即从99到0,依次递减
root=sqrt(n)
if root==int(root):
print n
break #如果没有break就会从81一直到1,如果有break,在81的时候就会结束循环
2.continue
当前迭代结束,跳到下一轮循环的开始,即跳过剩余循环,但不结束循环
for x in seq: #continue可以用下面的例子代替,故应习惯用break
if condition1:continue
if condition2:continue
do_sth()
do_sth_else()
etc()
for x in seq:
if not(condition1 or condition2):
do_sth()
do_sth_else()
etc

3.while True/break习语
while True实现了永不会自停的循环,加入if和break后,可以再循环内部任何地方终止循环(while循环只在开头)、
if/break将循环为成2部分,第一部分负责初始化,第二部分则在循环条件为真的情况下使用第一部分内初始化好的数据
eg: while True:
word=raw_input('word:')
if not word:break
print 'the word is ' ,word
5.56 循环中的else子句
eg: from math import sqrt
for n in range(99,81,-1):
root=sqrt(n)
if root==int(root):
print n
break
else:
print 'can\'t find it'


5.6 列表推导式--轻量级循环
是利用其他列表创建新列表,工作方式类似于for循环
eg: print [x*x for x in range(10)] #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print [x*x for x in range(10) if x % 3 == 0] #[0, 9, 36, 81]

gname=['Alice','Betty','Cici']
bname=['Chris','Andy','Bob']
firstletter={}
for girl in gname:
firstletter.setdefault(girl[0],[]).append(girl) #{'A': ['Alice'], 'C': ['Cici'], 'B': ['Betty']}
print [b+'--'+g for b in bname for g in firstletter[b[0]]] #['Chris--Cici', 'Andy--Alice', 'Bob--Betty']

5.7 三人行
pass、del、exec
5.71 什么都没发生
pass:在代码中做占位符使用,比如程序需要一个if语句,进行测试,但缺少一个语句块:
eg: if name=='ABC':
print 'Welcome'
elif name=='CBA':
#....
elif name=='XXXX'
print 'Access denied'
因为Python中空代码块是非法的,故代码不会执行,解决方法就是在语句块中加pass
elif name=='CBA':
pass
5.72 使用del删除
python会删除那些不再使用的对象
eg: source={'ABC':123}
test=source
source=None
test=None
test和source绑在同一字典上,source为None后,test还可用,但test也是None后,字典就漂在内存中,因为没有任何名字绑定到它上了,就没办法获取和使用,python就直接删除这个字典。此处除使用None外,也可用其他值
除了这个方法,也可使用del语句,它不仅会移除一个对象的引用,也会移除名字本身
eg: x=1
del x
print x #会报错:name 'x' is not defined
x=['hello','world']
y=x
y[1]=['python']
print x #hello python
del x
print y #hello python
x和y都指向同一个列表,但删除x并不影响y,原因就是删除的只是名称,而不是列表本身,实际上python没有方法删除值,是又解释器负责内存的回收
5.73 使用exec和eval执行和求值字符串
有时需动态创造python代码,然后将其作为语句执行或作为表达式计算,但会有潜在的安全漏洞,尤其在网络应用程序,比如cgi脚本中
1.exec
exec "print 'hello,world!'" #hello,world!
使用简单形式的exec不是好事,应该给它提供命名空间(放置变量的地方),从而使代码不会干扰命名空间(即改变你的变量)
eg: from math import sqrt
exec "sqrt=1"
sqrt(4) #error:object is not callable
通过使用in scope来保存变量
eg: from math import sqrt
scope={}
exec 'sqrt=1' in scope
sqrt(4) #2.0
print scope['sqrt'] #1
2.eval
eval用于求值,exec会执行python语句,而eval会计算python表达式,并返回结果;exec并不返回对象,因为它本身就是语句
eg: print eval(raw_input("Enter an arithmetic expression:"))

阅读(571) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~