第5章 条件,循环和其他语句

1. print 和 import 的更多信息

提示
对于很多应用程序来说,使用logging模块记日志比print语句更合适.

1.1 使用逗号输出

1
2
3
4
5
>>> name = 'kevin'
>>> age = 19
>>> print name,age
kevin 19
>>>

1.2 把某些事作为另一件事导入

从模块导入函数,通常可以使用 :

  • import somemodule
  • from somemodule import somefunction
  • from somemodule import somefunction,anotherfunction,yetanotherfuction
  • from somemodule import *

如果两个模板都有相同函数,可以在语句末尾增加一个as子句,在子句后给出想要的别名.

1
2
3
4
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>>

或者为函数提供别名

1
2
3
4
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
>>>

2. 赋值魔法

2.1 序列解包

多个赋值的操作可以同时进行 :

1
2
3
4
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>>

交换两个(或多个)变量 :

1
2
3
4
>>> x,y = y,x
>>> print x,y,z
2 1 3
>>>

还可以这样玩 :

1
2
3
4
5
6
7
>>> values = 1,2,3
>>> values
(1, 2, 3)
>>> x,y,z = values
>>> x
1
>>>

2.2 链式赋值

链式赋值(chained assignment) 是将同一个值赋给多个变量的捷径.

x = y = somefunction()

2.3 增量赋值

x = x + 1 等于 x+=1

3. 语句块 : 缩排的乐趣

注意
使用tab字符也可以缩进语句块.Python将一个tab字符解释为到下一个tab字符位置的移动,而一个tab字符位置为8个空格,但是标准且推荐的方式是只用空格,尤其是在每个缩进需要4个空格的时候.

4. 条件和条件语句

4.1 这就是布尔变量的作用

下面的值作为布尔表达式的时候,会被解释器看做假(false)
False None 0 "" () [] {}

注意
尽管[]和””都是假值,但是它们本身不相等.

4.2 条件执行和if语句

1
2
3
4
5
6
7
What is your name?kevin
>>> if name.endswith('kevin'):
print 'hello'+name
hellokevin
>>>

4.3 else语句

1
2
3
4
5
6
7
8
What is your name?kevin
>>> if name.endswith('kevin') :
print 'hello'+name
else :
print 'hello'
hellokevin
>>>

4.4 elif子句

elif是else if的简写

4.5 嵌套代码块

1
2
3
4
5
6
7
8
9
10
name = raw_input("What is your name?")
if name.endswith('Gumby'):
if name.startswith('Mr.'):
print 'Hello,Mr.Gumby'
elif name.startswith('Mrs.'):
print 'Hello,Mrs.Gumby'
else:
print 'Hello,Gumby'
else:
print 'hello,stranger'

4.6 更复杂的条件

表达式 描述
x is y x和y是同一个对象
x is not y x和y是不同的对象
x in y x是y容器(例如,序列)的成员
x not in y x不是y容器(例如,序列的)成员

相等运算符 ‘foo’ = ‘foo’

is : 同一性运算符
is 运算符是判定同一性而不是相等性.变量x和变量y都被绑定到同一个列表上,而变量z被绑定在另外一个具有相同数值和顺序的列表上.

总结 : 使用 == 运算符来判定两个对象是否相等,使用is判定两者是否相同(同一个对象).

4.7 断言

1
2
3
4
5
6
7
8
9
The number is positive
>>> age = -1
>>> assert 0 <age<100
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
assert 0 <age<100
AssertionError

5. 循环

  • while 循环 :
1
2
3
4
x = 1
while x<=100:
print x
x+=1
  • for 循环 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> words = ['this','is','an','ex']
>>> for word in words:
print word
this
is
an
ex
# 或者:
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 或者 :
>>>
  • 循环遍历字典元素
1
2
3
4
5
6
7
8
9
>>> d = {'x':1,'y':2,'z':3}
>>> for key in d:
print key,d[key]
y 2
x 1
z 3
>>>

5.4 一些迭代工具

  • 并行迭代
1
2
3
4
5
6
7
>>> names = ['kevin','leona']
>>> ages = [22,21]
>>> for i in range(len(names)):
print names[i],ages[i],'years old'
kevin 22 years old
leona 21 years old

5.5 跳出循环

break : 结束本次循环
continue : 跳过本次循环

6. 列表推导式 - 轻量级循环

列表推导式(List comprehension) 是利用其他列表创建新列表.

1
2
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

7. 总结

函数 描述
chr(n) 当传入序号n时,返回n所代表的包含一个字符的字符串,(0<=n<256)
eval(source[,globals[,locals]]) 将字符串作为表达式计算,并且返回值
enumerate(seq) 产生用于迭代(索引,值)对
ord(c) 返回单字符字符串的int值
range([start,]stop[,step]) 创建整数的列表
reversed(seq) 产生seq中值的反向版本,用于迭代
sorted(seq[,cmp][,key][,reverse]) 返回seq中值排序后的列表
xrange([start,]stop[,step]) 创建xrange对象用于迭代
zip(seq1,seq2) 创建用于并行迭代的新序列