pass, del, exec语句的用法。
有些自以为已经掌握的知识点,还隐藏着一些让人惊讶的特性。
* 使用逗号输出 *
>>> 1, 2, 3 (1, 2, 3) >>> print 1, 2, 3 # print 参数并不能像我们预期那样构成一个元组 1 2 3 >>> print (1, 2, 3) (1, 2, 3) >>> 'age', 42 ('age', 42) >>> name = 'Gumby' >>> mr = 'Mr' >>> greeting = 'Hello' >>> print name, mr, greeting Gumby Mr Hello >>> import math as abc #别名 >>> abc.sqrt(4) 2.0 >>> from math import sqrt as bcd # 为函数提供别名 >>> bcd(4) 2.0# 序列解包
>>> 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 # popitem 将键值作为元组返回 >>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'} >>> key, value = scoundrel.popitem() >>> key 'girlfriend' >>> value 'Marion'
* 链式赋值 *
x = y = somefunction()* 增量赋值 *
>>> x = 2 >>> x += 1 >>> x *= 2 >>> x 6 >>> fnord = 'foo' >>> fnord += 'bar' >>> fnord *= 2 >>> fnord 'foobarfoobar'* 语句块 : 缩排的乐趣 *
在 Python中,冒号 (:) 用来标识语句块的开始
* 条件和条件语句 布尔值*
下面的值在作为布尔表达式的时候,会被解释器看作假 (false)
False, None, 0, "", (), [], {}
>>> bool("") False >>> bool(42) True if 的使用 num = input('Enter a number : ') if num > 0: print 'positive' elif num < 0: print 'negative' else : print 'zero'更复杂的条件
*1, 比较运算符 x == y, x <= y, x is y, x is not y, x in y, x not in y
在Python中比较运算和赋值运算一样是可以连接的。
a if b else c* 断言 *
>>> age = 10 >>> assert 0 < age < 100 >>> assert 0 < age < 10 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError, * while 循环 * ---while1.py--- x = 1 while x <= 100: print x x += 1 ---while2.py --- name = '' while not name.strip(): name = raw_input('Please enter your name: ') print 'Hello, %s!' % name* for 循环 * 比while更简洁,应该尽量多用!
>>> numbers = range(10) >>> for i in numbers : print i* 循环遍历字典元素 *
>>> d = {'x' : 1, 'y' : 2, 'z' : 3} >>> for key in d : print key, 'corresponds to', d[key] ... y corresponds to 2 x corresponds to 1 z corresponds to 3 >>> for key, value in d.items(): print key, 'corresponds to', value ... y corresponds to 2 x corresponds to 1 z corresponds to 3* 一些迭代工具 *
(1) 并行迭代
>>> names = ['anne', 'beth', 'george', 'damon'] >>> ages = [12, 45, 32, 102] >>> for i in range(len(name)): print names[i], ages[i] anne 12 beth 45 george 32 damon 102 >>> zip(names , ages) [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)] >>> for name, age in zip(name, ages): print name, age anne 12 beth 45 george 32 damon 102(2) 编号迭代
for index, string in enumerate(strings): if 'xxx' in string: strings[index] = '[censored]'这个函数可以在提供索引的地方迭代索引-值对
(3) 翻转和排序迭代
>>> sorted([4,3, 6, 2, 6, 3, 8]) [2, 3, 3, 4, 6, 6, 8] >>> 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'] >>> ''.join(reversed('Hello,world')) 'dlrow,olleH'