if condtion: statement elif condition2: statement2 else: statement3
实用功能
列表推导式
1 2 3 4 5
#列表推导式,也适用于集合、字典 values = [10,21,3,5,12] squares = [x**2for x in values if x<=10] square_set = {x**2for x in values if x<=10} square_dict = {x: x**2for x in values if x<=10}
defsum(lst): """ Sum the values in a list """ tot = 0 for value in lst: tot = tot + value return tot
defadd(x, y): " Add two values." a = x + y return a
deftest(): w = [0,1,2,3] assert(sum(w) == 6) print'test passed.' if __name__ == '__main__': test()
这样的文件既可以当模块调用,也可以当脚本运行。
1 2 3 4 5
>>>run mymodule.py test passed >>>import mymodule as my >>>my.PI 3.1416
包(package)
假设我们有这样的一个文件夹:
foo/
__init__.py
bar.py (defines func)
baz.py (defines zap)
这意味着 foo 是一个package,可以这样导入其中的内容:
1 2
from foo.bar import func from foo.baz import zap
bar 和 baz 都是 foo 文件夹下的 .py 文件。
导入包要求:
文件夹 foo 在Python的搜索路径中
__init__.py 表示 foo 是一个包,它可以是个空文件。
异常exception
通过try….except来避免系统报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import math
whileTrue: try: text = raw_input('> ') if text[0] == 'q': break x = float(text) y = 1 / math.log10(x) print"1 / log10({0}) = {1}".format(x, y) except ValueError as exc: if exc.message == "math domain error": print"the value must be greater than 0" else: print"could not convert '%s' to float" % text except ZeroDivisionError: print"the value must not be 1" except Exception as exc: print"unexpected error:", exc.message