译文

10分钟学会Python[2]

翻译:令狐葱 | 2007-08-17 20:01:59 | 阅读2524 | 来源

10分钟学会Python[1]


9. 异常处理

Python中的异常处理使用try-except [exceptionname]程序块:
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之间。
  • 可以使用del删除数组中的元素或者变量。
  • List comprehensions[不知怎么翻译,译注]提供一个强大的方法来创建和操作list(列表)。它由一个后跟一个for语句的表达式组成,这个for语句后跟一个或者多个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
  • 全局变量可以声明在函数外边并且不需要任何特殊的声明就可以直接读取使用。但是如果你要改变该全局变量的值,你必须在函数的开始使用global关键字声明它,否则,Python将创建一个局部变量并给他赋值(要特别注意这点,不知道的话很容易犯错)。比如:
  • 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
13. 结束语

这个教程并没有列出Python的全部细节(甚至连一个子集都算不上)。Python还有一系列的库以及许多其他功能,这就需要你通过其他途径来学习了,比如很优秀的在线教程Dive into Python。我只希望这个教程能让你对Python快速上手。如果你觉得有什么需要改进或者添加的地方,或者你想看到的其他任何东西(类,错误处理,任何东西),那就在这里留言吧。

[完]




 

【免责声明:本文翻译仅为外语学习目的,原文作者个人观点与译者及译言网无关】

分享:

标签:program,Python,code,

本文共有2 条评论:

1楼 mmqq99 评论于 2007-10-17 16:42:37

内容翻译得不错,不过标题有点夸张,呵呵。10分钟快速入门差不多吧。

2楼 custjcy 评论于 2008-10-09 14:16:15

“list-comprehensions”是否可翻译为“列表推导”,这里有一篇翻译可供参考http://www.matrix.org.cn/resource/article/2007-09-24/e50bf5af-6a56-11dc-91f8-0da64dffe568.html

或者把"List comprehensions"翻译为"构造列表",这里有一篇翻译http://fy.py3k.cn/p/pydoc/tutorial/datastructures.html/ecn/

添加评论