def somefunction():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
>>> fnExcept()
Oops, invalid.
10. 包的导入
使用import [libname]导入外部包,你也可以为单独的函数使用from [libname] import [funcname]这种形式来导入。下面是一个例子:import random
from time import clock
randomint = random.randint(1, 100)
>>> print randomint
64
11.文件I/O
Python有一个很大的内建库数组来处理文件的读写。下面的例子展示如何使用Python的文件I/O来序列化(使用pickle把数据结构转换成字符串)。
import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = file(r"C:binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
myfile = file(r"C:text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
myfile = file(r"C:text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
# Open the file for reading.
myfile = file(r"C:binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]
[有关资料显示,使用另一个库CPickle效率比pickle高1000倍,因为CPickle使用C实现的,使用方法和pickle基本一样。译注]
12. 其他
1 < a < 3检查a是否介于1和3之间。if@ 或者 @for语句,就像这样:>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>> any(i % 3 for i in [3, 3, 4, 4, 3])
True
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
3
>>> del lst1[0]
>>> print lst1
[2, 3]
>>> del lst1
number = 5
def myfunc():
# This will print 5.
print number
def anotherfunc():
# This raises an exception because the variable has not
# been assigned to before printing. Python knows that it a
# value will be assigned to it later and creates a new, local
# number instead of accessing the global one.
print number
number = 3
def yetanotherfunc():
global number
# This will correctly change the global.
number = 3
【免责声明:本文翻译仅为外语学习目的,原文作者个人观点与译者及译言网无关】