控制语句
1、print语句
(1) 可以同时输出多个表达式,用“,”分割
>>> print 'Age:', 42
Age: 42
l 注意Tuple的使用:
>>> 1, 2, 3
(1, 2, 3)
>>> print 1, 2, 3
1 2 3
>>> print (1, 2, 3)
(1, 2, 3)
(2) 如果最后是“,”,则下一个print语句的结果在同行输出
print 'Hello,',
print 'world!'
输出:Hello, world!
2、import语句
(1) 基本格式
l import module_name
l from module_name import function_name
(2) 使用as子句
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
3、赋值
(1) Sequence拆分
l 同时赋值:
>>> x, y, z = 1, 2, 3
>>> print x, y, z
1 2 3
>>> x, y = y, x
>>> print x, y, z
2 1 3
l 将Sequence拆分到一组变量:
>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1
l 这最常用于接收函数或方法返回Tuple:
>>> scoundrel = {'name': 'Robin', 'girlfriend': ' Marion '}
>>> key, value = scoundrel.popitem()
>>> key
'girlfriend'
>>> value
' Marion '
(2) 串联赋值:将相同的值赋值给多个变量
>>> x=y=z=1
>>> x
1
>>> y
1
>>> z
1
(3) 扩展赋值
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x
6
>>> fnord = 'foo'
>>> fnord += 'bar'
>>> fnord
'foobar'
l 将大量小的String合并成一个大的String的一种比较好的方法:将小的String追加到List中,然后用String的join()方法生成大的String
4、语句块
l Python的语句块以“:”开始,同一个语句块的每个语句的缩进都相同
5、条件和条件语句
(1) Python会将下面的值解释为false:
False None 0 "" () [] {}
(2) if-else-elif
num = input('Enter a number: ')
if num > 0:
print 'The number is positive'
elif num < 0:
print 'The number is negative'
else:
print 'The number is zero'
(3) 比较操作符
== > < >= <= != is is not in not in
l 可以使用串联比较:
0 < age < 100
l is和==的区别:前者指对象本身,后者指对象的值
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
(4) 逻辑操作符
and or not
l 逻辑操作符只计算必要的表达式,以得到True或False结果:
name = raw_input('Please enter your name: ') or '<unknown>'
(5) assert语句
l assert语句可以作为断点在程序中使用,并可以加一个String作为解释:
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AssertionError: The age must be realistic