金牌译作 10分钟学会Python[1]

1895个读者 翻译: 令狐葱  08/15/2007 原文 引用 双语对照及眉批 字体大小

1. 准备工作

哦,你是要学习Python编程语言但是又苦于找不到一个简洁但是全面的教程么?这个教程就是要试图在10分钟内让你掌握Python。可能它有点不像一个教程,或者说应该介于教程和cheatsheet[可以快速查找的一个简单表单,不知道怎么翻译,译注]之间,所以在这里我只能向你展示一些最基本的概念,旨在让你能够快速入门。显然,如果你真要学习一门编程语言,你需要使用它编码一段时间。我假定你已经有一些熟知的编程知识,因此在这里我就不再讲那些与语言无关的编程知识。教程中的关键字我都让它高亮显示,这样你就可以一眼就看清楚。另外,为了保持教程的简洁,一些知识就只在代码中展示,只有一些简单的注释。

2. 特性

Python是一个强类型(也就是类型都是强制指定的),动态,隐式类型的(即,你不需要声明变量),大小写敏感(var和VAR是两个不同的变量),面向对象(一切皆是对象)的语言。[专业术语翻译有点别扭,译注]

3. 语法

Python 没有命令结束标志,并且,使用缩进来区分程序块。块开始的时候缩进开始,块结束的时候缩进结束。声明需要一个:来引领一个缩进块。注释使用#开始并且只占一行。多行注释使用多行字符串。赋值使用等号(“=”),测试是否相等使用两个等号(“==”)。可以分别使用+=或者-=来增加或者减少变量值。这在多个数据结构上都适用,包括字符串。你也可以在一行上使用多个变量。举例来说:
>>> myvar = 3
>>> myvar += 2
>>> myvar -= 1
"""This is a multiline comment.
The following lines concatenate the two strings."
""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
>>> myvar, mystring = mystring, myvar

4. 数据类型

Python中可用的数据类型有列表、元组以及字典。在集合库中集合也可用。列表就像是以维数组(但是你还可以有列表的列表),字典就是关联数组(或者叫哈希表),元组就是不可变一维数组(Python中数组可以是任何类型,因此你可以在列表、字典或者元组中混合使用数字、字符串等数据类型)。在所有的数组类型中第一个元素的标号都是0,负数表示从后向前数,-1则表示最后一个元素。变量可以指向函数。用法如下:
>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again"
>>> mylist[-1] = 3.14
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.14
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print myfunction(mylist)
3
你可以使用:取到数组的一个范围,:前留空则表示从第一个元素开始,:后留空则表示直到最后一个元素。负值表示从后索引(即-1是最后一个元素)。如下所示:
>>> mylist = ["List item 1", 2, 3.14]
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[1:]
[2, 3.14]
5. 字符串

字符串可以使用单引号或者双引号,你可以在使用一个引号的里面嵌套使用另一种引号(也就是说,"He said 'hello'."是合法的)。多行字符串则使用三引号(单双皆可)。Python还可以让你设置Unicode编码,语法如下:u"This is a unicode string".使用值填充一个字符串的时候可以使用%(取模运算符)和一个元组。每个%s使用元组中的一个元素替换,从左到右。你还可以使用字典。如下所示:
>>>print "Name: %snNumber: %snString: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---
 
strString = """This is
a multiline
string."
""
 
# WARNING: Watch out for the trailing s in "%(key)s".
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.
6. 流程控制

流程控制使用while,if,以及for。没有select[和哪种语言对比?不知道。译注],使用if代替。使用for来列举列表中的元素。要得到一个数字的列表,可以使用range(<number>)。这些声明的语法如下:
rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
# Check if number is one of
# the numbers in the tuple.
if number in (3, 4, 7, 9):
# "Break" terminates a for without
# executing the "else" clause.
break
else:
# "Continue" starts the next iteration
# of the loop. It's rather useless here,
# as it's the last statement of the loop.
continue
else:
# The "else" clause is optional and is
# executed only if the loop didn't "break".
pass # Do nothing
 
if rangelist[1] == 2:
print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
print "The second item (lists are 0-based) is 3"
else:
print "Dunno"
 
while rangelist[1] == 1:
pass
7. 函数

函数使用def关键字。可选参数在必须参数之后出现,并且可以被赋一默认值。对命名参数而言,参数名参数名被赋一个值。函数可以返回一个元组(打开元组你就可以实现返回多个值)。Lanbda函数是个特例,它由一个表达式构成。参数使用引用传递,但是可变类型(元组,列表,数字,字符串等等)不能被改变。举例如下:

# arg2 and arg3 are optional, they have default values
# if one is not passed (100 and "test", respectively).
def myfunction(arg1, arg2 = 100, arg3 = "test"):
return arg3, arg2, arg1
 
>>>ret1, ret2, ret3 = myfunction("Argument 1", arg3 = "Named argument")
# Using "print" with multiple values prints them all, separated by a space.
>>> print ret1, ret2, ret3
Named argument 100 Argument 1
 
# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
8. 类

Python部分支持类的多重继承。私有变量和方法可以使用至少两个"_"开始并且至少一个"_"结束来声明,比如"__spam"(这只是约定,语言中并没有强制规定)。我们可以给类的实例赋任意的变量。请看下例:
class MyClass:
common = 10
def __init__(self):
self.myvariable = 3
def myfunction(self, arg1, arg2):
return self.myvariable
 
# This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will create a new one on the class
# instance and assign the value to that.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50
 
# This class inherits from MyClass. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
def __init__(self, arg1):
self.myvariable = 3
print arg1
 
>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10
继续阅读
  • 为什么小johnny不能编程?

    多月以前,David Brin(很多科幻小说以及“透明社会”的作者)为Salon写了一段文字,名叫为什么小johny不能编码,内容大概是说关于basic的消失,结果难以引导小孩简单编程。当我阅读这段...

  • 10分钟学会Python[2]

    10分钟学会Python[1] 9. 异常处理 Python中的异常处理使用try-except [exceptionname]程序块: def somefunction(): try: # Div...

  • 抓住你了!编程中的小麻烦

    Programming Gotchas 啊哈,抓住你了。程序设计中的小麻烦。

  • 实例分析: 使用 C 扩展 Python

    实例分析: 使用 C 扩展 Python

  • 百年语言

    百年语言 Paul Graham  2003年4月 (本文出自2003年Python大会上的一篇主题讲话)   很难预测人们的生活在一百年后会是什么样子,我们只能给很少的事物一个确切的预测。我们知道...

  • 蟒蛇热衷美国

    放弃宠爱在Everglades中饲养的缅甸蟒蛇,气候的变化将有可能使美国三分之一的地方成为潜在的蟒蛇栖息地。

标签:

内容有问题?请与我们联络。

译作评分

  • Currently 4.67/5
  • 1
  • 2
  • 3
  • 4
  • 5
 4.7  |  3 个评分

3条评论    3眉批

  • 1.

    雷声大雨点大 大学士 | Blog

    谢谢翻译!一直有朋友介绍说,不会python就不算会编程。。。加了一个小眉批。

    08/16/2007

  • 2.

    mingkg21 童生

    我还不会编程

    08/22/2007

  • 3.

    ZenoX 状元

    看到这样用心的翻译,  忍不住穿越了,  相见恨晚.
    yeeyan  的用户增长很迅速,  但有质量,  有分量的译文却没有多多少,  不知为什么.

    09/24/2008

添加评论

欢迎访问译言网。在这里,您可以。。。

阅读
发现
翻译