您的位置:首页 >> 编程开发 >> C/C++ >> 正文
RSS
 

Python Tutorial(1)

http://www.rdxx.com 05年09月13日 23:28 Blog.ChinaUnix.net 我要投稿

关键词: Tutorial , Python
python2.4的一个教程

前言 Front Matter

ALT=

Abstract:

Python is an easy to learn, powerful programminglanguage. It has efficient high-level data structures and asimple but effective approach to object-oriented programming.Python's elegant syntax and dynamic typing, together with itsinterpreted nature, make it an ideal language for scripting andrapid application development in many areas on most platforms.Python

是一种容易学习的强大语言。它包括了高效的高级数据结构,提供了一个简单但很有效的方式进行面向对象编程。Python优雅的语法,动态类型,以及它天然的解释能力,使其成为了大多数平台上应用于各领域理想的脚本语言以及开发环境。

The Python interpreter and the extensive standard library arefreely available in source or binary form for all major platformsfrom the Python Web site, http://www.python.org/, and can befreely distributed. The same site also contains distributions ofand pointers to many free third party Python modules, programs andtools, and additional documentation.

Python 解释器及其扩展标准库的源码和编译版本可以从 Python 的 Web站点, http://www.python.org/,及其所有镜像站上免费获得,并且可以自由发布。该站点上也提供了Python 的一些第三方模块,程序,工具,以及附加的文档。

The Python interpreter is easily extended with new functions and datatypes implemented in C or C++ (or other languages callable from C).Python is also suitable as an extension language for customizableapplications.

Python 的解释器很容易通过 C 或 C++(或者其它可以由C来调用的语言)来扩展新的函数和数据结构。因此Python 也很适于作为定制应用的一种扩展语言。

This tutorial introduces the reader informally to the basic conceptsand features of the Python language and system. It helps to have aPython interpreter handy for hands-on experience, but all examples areself-contained, so the tutorial can be read off-line as well.

这个手册介绍了一些 Python语言及其系统的基本知识与概念。这有助于读者对 Python有一个基本的认识,当然所有的例子都已包括在文中,所以这本手册很适合离线阅读。

For a description of standard objects and modules, see thePython Library Reference document. ThePython Reference Manual gives a moreformal definition of the language. To write extensions in C orC++, read Extending and Embedding thePython Interpreter and Python/C APIReference. There are also several books covering Python in depth.

需要有关标准对象和模块的详细介绍的话,请查询Python 库参考手册文档。Python 参考手册提供了更多的关于语言方面的正式说明。需要编写C或C++扩展,请阅读Python 解释器的扩展和集成 以及Python/C API参考手册。这几本书涵盖了各个深度上的Python知识。

This tutorialdoes not attempt to be comprehensive and cover every singlefeature, or even every commonly used feature. Instead, itintroduces many of Python's most noteworthy features, and willgive you a good idea of the language's flavor and style. Afterreading it, you will be able to read and write Python modules andprograms, and you will be ready to learn more about the variousPython library modules described in thePython Library Reference.

本手册不会涵盖 Python的所有功能,也不会去解释所用到的所有相关的知识。相反,它介绍了许多Python中最引人注目的功能,这会对读者掌握这门语言的风格大有帮助。读过它后,你应该可以阅读和编写Python 模块和程序,接下来可以从 Python库参考手册 中进一步学习Python复杂多变的库和模块。

1. 开胃菜 Whetting Your Appetite

If you ever wrote a large shell script, you probably know thisfeeling: you'd love to add yet another feature, but it's alreadyso slow, and so big, and so complicated; or the feature involves asystem call or other function that is only accessible from C...Usually the problem at hand isn't serious enough to warrantrewriting the script in C; perhaps the problem requiresvariable-length strings or other data types (like sorted lists offile names) that are easy in the shell but lots of work toimplement in C, or perhaps you're not sufficiently familiar withC.

如果你写过大规模的 Shell脚本,应该会有过这样的体会:你还非常想再加一些别的功能进去,但它已经太大、太慢、太复杂了;或者这个功能需要调用一个系统函数,或者它只适合通过C 来调用 ...通常这些问题还不足以严肃到需要用 C重写这个脚本;可能这个功能需要一些类似变长字符串或其它一些在 Shell脚本中很容易找到的数据类型(比如文件名的有序列表),但它们用 C来实现就要做大量的工作,或者,你对 C 还不是很熟悉。

Another situation: perhaps you have to work with several C libraries,and the usual C write/compile/test/re-compile cycle is too slow. Youneed to develop software more quickly. Possibly perhaps you'vewritten a program that could use an extension language, and you don'twant to design a language, write and debug an interpreter for it, thentie it into your application.

另一种情况:可能你需要使用几个 C 库来工作,通常 C的编写/编译/测试/重编译周期太慢。你需要尽快的开发软件。也许你需要写一个使用扩展语言的程序,但不想设计一个语言,并为此编写调试一个解释器,然后再把它集成进你的程序。

In such cases, Python may be just the language for you. Python issimple to use, but it is a real programming language, offeringmuch more structure and support for large programs than the shellhas. On the other hand, it also offers much more error checkingthan C, and, being a very-high-level language, it hashigh-level data types built in, such as flexible arrays anddictionaries that would cost you days to implement efficiently inC. Because of its more general data types Python is applicable toa much larger problem domain than Awk or even Perl,yet many things are at least as easy in Python as in thoselanguages.

遇到以上情况,Python 可能就是你要找的语言。Python很容易上手,但它是一门真正的编程语言,相对于Shell,它提供的针对大型程序的支持和结构要多的多。另一方面,它提供了比C更多的错误检查,并且,做为一门高级语言,它拥有内置的高级数据类型,例如可变数组和字典,如果通过C来实现的话,这些工作可能让你大干上几天的时间。因为拥有更多的通用数据类型,Python适合比 Awk 甚至 Perl更广泛的问题领域,在其它的很多领域,Python至少比别的语言要易用得多。

Python allows you to split up your program in modules that can bereused in other Python programs. It comes with a large collectionof standard modules that you can use as the basis of your programs-- or as examples to start learning to program in Python. Thereare also built-in modules that provide things like file I/O,system calls, sockets, and even interfaces to graphical userinterface toolkits like Tk.

Python 可以让你把自己的程序分隔成不同的模块,以便在其它的 Python程序中重用。这样你就可以让自己的程序基于一个很大的标准模块集或者用它们做为示例来学习Python 编程。Python 中集成了一些类似文件I/O,系统调用,sockets,甚至像 Tk 这样的用户图形接口。

Python is an interpreted language, which can save you considerable timeduring program development because no compilation and linking isnecessary. The interpreter can be used interactively, which makes iteasy to experiment with features of the language, to write throw-awayprograms, or to test functions during bottom-up program development.It is also a handy desk calculator.

Python是一门解释型语言,因为不需要编译和链接的时间,它可以帮你省下一些开发时间。解释器可以交互式使用,这样就可以很方便的测试语言中的各种功能,以便于编写发布用的程序,或者进行自下而上的开发。还可以当它是一个随手可用的计算器。

Python allows writing very compact and readable programs. Programswritten in Python are typically much shorter than equivalent C orC++ programs, for several reasons:Python 可以写出很紧凑和可读性很强的程序。用 Python写的程序通常比同样的 C 或 C++程序要短得多,这是因为以下几个原因:

  • the high-level data types allow you to express complexoperations in a single statement;
  • statement grouping is doneby indentation instead of beginning and ending brackets;
  • novariable or argument declarations are necessary.

高级数据结构使你可以在一个单独的语句中表达出很复杂的操作;语句的组织依赖于缩进而不是 begin/end 块; 不需要变量或参数声明。

Python is extensible: if you know how to program in C it is easyto add a new built-in function or module to the interpreter, either toperform critical operations at maximum speed, or to link Pythonprograms to libraries that may only be available in binary form (suchas a vendor-specific graphics library). Once you are really hooked,you can link the Python interpreter into an application written in Cand use it as an extension or command language for that application.

Python 是 可扩展的:如果你会用 C语言写程序,那就可以很容易的为解释器添加新的集成模块和功能,或者优化瓶颈,使其达到最大速度,或者使Python能够链接到所需的二进制架构上(比如某个专用的商业图形库)。等你真正熟悉这一切了,你就可以把Python 集成进由 C 写成的程序,把 Python当做这个程序的扩展或命令行语言。

By the way, the language is named after the BBC show ``MontyPython's Flying Circus'' and has nothing to do with nastyreptiles. Making references to Monty Python skits indocumentation is not only allowed, it is encouraged!

顺便说一下,这个语言的名字来源于 BBC 的“Monty Python's FlyingCircus”节目,和凶猛的爬虫没有任何关系。在文档中引用 Monty Python典故不仅是允许的,而且还受到鼓励!

Now that you are all excited about Python, you'll want to examine itin some more detail. Since the best way to learn a language isusing it, you are invited here to do so.

现在你已经了解了 Python中所有激动人心的东西,大概你想仔细的试试它了。学习一门语言最好的办法就是使用它,你会很乐于这样做。

In the next chapter, the mechanics of using the interpreter areexplained. This is rather mundane information, but essential fortrying out the examples shown later.

下一节中,我们会很机械的说明解释器的用法。这没有什么神秘的,不过有助于我们练习后面展示的例子。

The rest of the tutorial introduces various features of the Pythonlanguage and system through examples, beginning with simpleexpressions, statements and data types, through functions and modules,and finally touching upon advanced concepts like exceptionsand user-defined classes.

本指南其它部分通过例子介绍了 Python语言和系统的各种功能,开始是简单表达式、语法和数据类型,接下来是函数和模块,最后是诸如异常和自定义类这样的高级内容。

2. 使用Python解释器 Using the Python Interpreter


2.1 调用解释器 Invoking the Interpreter

The Python interpreter is usually installed as/usr/local/bin/python on those machines where it isavailable; putting /usr/local/bin in your Unix shell'ssearch path makes it possible to start it by typing the command

通常 Python 的解释器被安装在目标机器的/usr/local/bin/python 目录下;把 /usr/local/bin目录放进你的Unix Shell 的搜索路径里,确保它可以通过输入

python

to the shell. Since the choice of the directory where theinterpreter lives is an installation option, other places arepossible; check with your local Python guru or systemadministrator. (E.g., /usr/local/python is a popularalternative location.)

来启动。因为安装路径是可选的,所以也有可能安装在其它位置,你可以与安装Python的用户或系统管理员联系。(例如,/usr/local/python就是一个很常见的选择)

Typing an end-of-file character (Control-D on Unix,Control-Z on Windows) at the primary prompt causes theinterpreter to exit with a zero exit status. If that doesn'twork, you can exit the interpreter by typing the followingcommands: "import sys; sys.exit()".

输入一个文件结束符(Unix上是Ctrl+D,Windows上是Ctrl+Z)解释器会以0值退出(就是说,没有什么错误,正常退出--译者)。如果这没有起作用,你可以输入以下命令退出:"importsys; sys.exit()"。

The interpreter's line-editing features usually aren't verysophisticated. On Unix, whoever installed the interpreter mayhave enabled support for the GNU readline library, which adds moreelaborate interactive editing and history features. Perhaps thequickest check to see whether command line editing is supported istyping Control-P to the first Python prompt you get. If it beeps,you have command line editing; see Appendix foran introduction to the keys. If nothing appears to happen, or ifP is echoed, command line editing isn't available; you'llonly be able to use backspace to remove characters from thecurrent line.

解释器的行编辑功能并不很复杂。装在Unix上的解释器可能会有GNUreadline库支持,这样就可以额外得到精巧的交互编辑和历史记录功能。可能检查命令行编辑器支持能力最方便的方式是在主提示符下输入Ctrl-P。如果有嘟嘟声(计算机扬声器),说明你可以使用命令行编辑功能,从附录A 可以查到快捷键的介绍。如果什么也没有发声,或者P显示了出来,说明命令行编辑功能不可用,你只有用退格键删掉输入的命令了。

The interpreter operates somewhat like the Unix shell: when calledwith standard input connected to a tty device, it reads and executescommands interactively; when called with a file name argument or witha file as standard input, it reads and executes a script fromthat file.

解释器的操作有些像 UnixShell:使用终端设备做为标准输入来调用它时,解释器交互的解读和执行命令,通过文件名参数或以文件做为标准输入设备时,它从文件中解读并执行脚本

A second way of starting the interpreter is"python -c command [arg] ...", whichexecutes the statement(s) in command, analogous to the shell's-c option. Since Python statements often contain spacesor other characters that are special to the shell, it is best to quotecommand in its entirety with double quotes.

启动解释器的第二个方法是"python -ccommand [arg]...",这种方法可以在命令行中直接执行语句,等同于Shell的-c选项。因为Python语句通常会包括空格之类的特殊字符,所以最好把整个语句用双引号包起来。

Note that there is a difference between "python file" and"python <file". In the latter case, input requests from theprogram, such as calls to input() and raw_input(), aresatisfied from file. Since this file has already been readuntil the end by the parser before the program starts executing, theprogram will encounter end-of-file immediately. In the former case(which is usually what you want) they are satisfied from whatever fileor device is connected to standard input of the Python interpreter.

注意"python file"和"python<file"是有区别的。对于后一种情况,程序中类似于调用input()raw_input()这样的输入请求,来自于确定的文件。因为在解析器开始执行之前,文件已经完全读入,所以程序指向文件尾。在前一种情况(这通常是你需要的)它们从来自于任何联接到Python 解释器的标准输入,无论它们是文件还是其它设备。

When a script file is used, it is sometimes useful to be able torun the script and enter interactive mode afterwards. This can bedone by passing -i before the script. (This does notwork if the script is read from standard input, for the samereason as explained in the previous paragraph.)

使用脚本文件时,经常会运行脚本然后进入交互模式。这也可以通过在脚本之前加上-i参数来实现。(如果脚本来自标准输入,就不能这样运行,与前一段提到的原因一样。)


2.1.1 参数传递 Argument Passing

When known to the interpreter, the script name and additionalarguments thereafter are passed to the script in the variablesys.argv, which is a list of strings. Its length is at leastone; when no script and no arguments are given, sys.argv[0] isan empty string. When the script name is given as '-' (meaningstandard input), sys.argv[0] is set to '-'. When-c command is used, sys.argv[0] is set to'-c'. Options found after -c command arenot consumed by the Python interpreter's option processing but left insys.argv for the command to handle.

调用解释器时,脚本名和附加参数之传入一个名为 sys.argv的字符串列表。没有脚本和参数时,它至少也有一个元素:sys.argv[0] 此时为空字符串。脚本名指定为 '-'(表示标准输入)时, sys.argv[0]被设置为'-',使用-c 指令 时, sys.argv[0]被设定为'-c'-c 命令之后的参数不会被Python 解释器的选项处理机制所截获,而是留在sys.argv中,供脚本命令操作。


2.1.2 交互模式 Interactive Mode

When commands are read from a tty, the interpreter is said to bein interactive mode. In this mode it prompts for the nextcommand with the primary prompt, usually three greater-thansigns (">>"); for continuation lines it prompts withthe secondary prompt, by default three dots ("... ").The interpreter prints a welcome message stating its versionnumber and a copyright notice before printing the first prompt:

从 tty 读取命令时,我们称解释器工作于 交互模式。这种模式下它根据 主提示符来执行,主提示符通常标识为三个大于号( ">>");继续的部分被称为 从属提示符 ,由三个点标识("... ")。在第一行之前,解释器打印欢迎信息、版本号和授权提示:

python
Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>

Continuation lines are needed when entering a multi-line construct.As an example, take a look at this if statement:

输入多行结构时需要从属提示符了,例如,下面这个 if语句:

>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be careful not to fall off!"
...
Be careful not to fall off!


2.2 解释器及其环境 The Interpreter and Its Environment


2.2.1 错误处理 Error Handling

When an error occurs, the interpreter prints an errormessage and a stack trace. In interactive mode, it then returns tothe primary prompt; when input came from a file, it exits with anonzero exit status after printingthe stack trace. (Exceptions handled by an except clause in atry statement are not errors in this context.) Some errors areunconditionally fatal and cause an exit with a nonzero exit; thisapplies to internal inconsistencies and some cases of running out ofmemory. All error messages are written to the standard error stream;normal output from the executed commands is written to standardoutput.

有错误发生时,解释器打印一个错误信息和栈跟踪器。交互模式下,它返回主提示符,如果从文件输入执行,它在打印栈跟踪器后以非零状态退出。(异常可以由try 语句中的 except子句来控制,这样就不会出现上文中的错误信息)有一些非常致命的错误会导致非零状态下退出,这由通常由内部矛盾和内存溢出造成。所有的错误信息都写入标准错误流;命令中执行的普通输出写入标准输出。

Typing the interrupt character (usually Control-C or DEL) to theprimary or secondary prompt cancels the input and returns to theprimary prompt.2.1 Typing an interrupt while a command is executing raises theKeyboardInterrupt exception, which may be handled by atry statement.

在主提示符或附属提示符输入中断符(通常是Control-C orDEL)就会取消当前输入,回到主命令行。 2.2.执行命令时输入一个中断符会抛出一个KeyboardInterrupt 异常,它可以被 try句截获。


2.2.2 执行Python脚本 Executable Python Scripts

On BSD'ish Unix systems, Python scripts can be made directlyexecutable, like shell scripts, by putting the line

BSD类的 Unix系统中,Python 脚本可以像 Shell脚本那样直接执行。只要在脚本文件开头写一行命令,指定文件和模式:

#! /usr/bin/env python

(assuming that the interpreter is on the user's PATH) atthe beginning of the script and giving the file an executablemode. The "#!" must be the first two characters of thefile. On some platforms, this first line must end with aUnix-style line ending ("\n"), not a Mac OS("\r") or Windows ("\r\n") line ending.Note that the hash, or pound, character, "#", is usedto start a comment in Python.

(将用户路径通知解释器) "#!"必须是文件的前两个字符,在某些平台上,第一行必须以 Unix风格的行结束符("\n")结束,不能用Mac("r")或Windows("\rn")的结束符。注意,"#"是Python中是行注释的起始符。

The script can be given a executable mode, or permission, usingthe chmod command:

脚本可以通过 chmod 命令指定执行模式和许可权。

$ chmod +x myscript.py

2.2.3 源程序编码 Source Code Encoding

It is possible to use encodings different than ASCII in Python sourcefiles. The best way to do it is to put one more special comment lineright after the #! line to define the source file encoding:

Python 的源文件可以通过编码使用 ASCII 以外的字符集。最好的做法是在 #! 行后面用一个特殊的注释行来定义字符集。

# -*- coding: iso-8859-1 -*-

With that declaration, all characters in the source file will be treated asiso-8859-1, and it will bepossible to directly write Unicode string literals in the selectedencoding. The list of possible encodings can be found in thePython Library Reference, in the sectionon codecs.

根据这个声明,Python 会将文件中的字符尽可能的从指定的编码转为Unicode,在本例中,这个字符集是 iso-8859-1 。在Python 库参考手册codecs部份可以找到可用的编码列表(根据个人经验,推荐使用cp-936或utf-8处理中文--译者注)。

If your editor supports saving files as UTF-8 with a UTF-8byte order mark (aka BOM), you can use that instead of anencoding declaration. IDLE supports this capability ifOptions/General/Default Source Encoding/UTF-8 is set. Noticethat this signature is not understood in older Python releases (2.2and earlier), and also not understood by the operating system for#! files.

如果你的文件编辑器支持 UTF-8 格式,并且可以保存UTF-8 标记(aka BOM - Byte OrderMark),你可以用这个来代替编码声明。IDLE可以通过设定Options/General/DefaultSource Encoding/UTF-8来支持它。需要注意的是旧版Python不支持这个标记(Python2.2或更早的版本),同样支持#!文件的操作系统也不会支持它(即#!和# -*- coding: -*- 二者必择其一——译者)。

By using UTF-8 (either through the signature or an encodingdeclaration), characters of most languages in the world can beused simultaneously in string literals and comments. Usingnon-ASCIIcharacters in identifiers is not supported. To displayall these characters properly, your editor must recognize that thefile is UTF-8, and it must use a font that supports all thecharacters in the file.

使用 UTF-8内码(无论是用标记还是编码声明),我们可以在字符串和注释中使用世界上的大部分语言。标识符中不能使用非ASCII字符集。为了正确显示所有的字符,你一定要在编辑器中将文件保存为UTF-8 格式,而且要使用支持文件中所有字符的字体。


2.2.4 交互式环境的启动文件 The Interactive Startup File

When you use Python interactively, it is frequently handy to have somestandard commands executed every time the interpreter is started. Youcan do this by setting an environment variable namedPYTHONSTARTUP to the name of a file containing your start-upcommands. This is similar to the .profile feature of theUnix shells.

使用 Python解释器的时候,我们可能需要在每次解释器启动时执行一些命令。你可以在一个文件中包含你想要执行的命令,设定一个名为PYTHONSTARTUP 的环境变量来指定这个文件。这类似于 Unixshell的 .profile 文件。

This file is only read in interactive sessions, not when Python readscommands from a script, and not when /dev/tty is given as theexplicit source of commands (which otherwise behaves like aninteractive session). It is executed in the same namespace whereinteractive commands are executed, so that objects that it defines orimports can be used without qualification in the interactive session.You can also change the prompts sys.ps1 and sys.ps2 inthis file.

这个文件在交互会话期是只读的,当 Python 从脚本中解读文件或以终端/dev/tty做为外部命令源时则不会如此(尽管它们的行为很像是处在交互会话期。)它与解释器执行的命令处在同一个命名空间,所以由它定义或引用的一切可以在解释器中不受限制的使用。你也可以在这个文件中改变sys.ps1sys.ps2 指令。

If you want to read an additional start-up file from the currentdirectory, you can program this in the global start-up file using codelike "if os.path.isfile('.pythonrc.py'):execfile('.pythonrc.py')". If you want to use the startup file in ascript, you must do this explicitly in the script:

如果你想要在当前目录中执行附加的启动文件,可以在全局启动文件中加入类似以下的代码:"if os.path.isfile('.pythonrc.py'):execfile('.pythonrc.py')"。如果你想要在某个脚本中使用启动文件,必须要在脚本中写入这样的语句:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)



Footnotes

... prompt.2.1
A problem with the GNU Readline package may prevent this.
...DEL)就会取消当前输入,回到主命令行。2.2
GNU readline包的一个错误可能会造成无法正常工作。



3. Python简介 An Informal Introduction to Python

In the following examples, input and output are distinguished by thepresence or absence of prompts (">>" and "... "): to repeatthe example, you must type everything after the prompt, when theprompt appears; lines that do not begin with a prompt are output fromthe interpreter. Note that a secondary prompt on a line by itself in an example meansyou must type a blank line; this is used to end a multi-line command.

在后面的例子中,区分输入和输出的方法是看是否有提示符("»> "和"... "):想要重现这些例子的话,你就要在提示符显示后输入所有的一切;没有以提示符开始的行,是解释器输出的信息。需要注意的是示例中的从属提示符用于多行命令的结束,它表示你需要输入一个空行。

Many of the examples in this manual, even those entered at theinteractive prompt, include comments. Comments in Python start withthe hash character, "#", and extend to the end of thephysical line. A comment may appear at the start of a line orfollowing whitespace or code, but not within a string literal. A hashcharacter within a string literal is just a hash character.

本手册中的很多示例都包括注释,甚至有一些在交互提示符中折行。Python中的注释以符号"#"起始,一直到当前行的结尾。注释可能出现在一行的开始,也可能跟在空格或程序代码之后,但不会出现在字符串中,字符串中的"#" 号只代表 "#" 号。

Some examples:

示例:

# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."


3.1 将Python当作计算器使用 Using Python as a Calculator

Let's try some simple Python commands. Start the interpreter and waitfor the primary prompt, ">>". (It shouldn't take long.)

让我们试验一些简单的 Python命令。启动解释器然后等待主提示符">>"出现(这用不了太久)。


3.1.1 数值 Numbers

The interpreter acts as a simple calculator: you can type anexpression at it and it will write the value. Expression syntax isstraightforward: the operators +, -, * and/ work just like in most other languages (for example, Pascalor C); parentheses can be used for grouping. For example:

解释器的行为就像是一个计算器。你可以向它输入一个表达式,它会返回结果。表达式的语法简明易懂:+-*/和大多数语言中的用法一样(比如C或Pascal),括号用于分组。例如:

>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3

Like in C, the equal sign ("=") is used to assign a value to avariable. The value of an assignment is not written:

像c一样,等号("=")用于给变量赋值。被分配的值是只读的。

>>> width = 20
>>> height = 5*9
>>> width * height
900

A value can be assigned to several variables simultaneously:

同一个值可以同时赋给几个变量:

>>> x = y = z = 0  # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

There is full support for floating point; operators with mixed typeoperands convert the integer operand to floating point:

Python完全支持浮点数,不同类型的操作数混在一起时,操作符会把整型转化为浮点数。

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

Complex numbers are also supported; imaginary numbers are written witha suffix of "j" or "J". Complex numbers with a nonzeroreal component are written as "(real+imagj)", or canbe created with the "complex(real, imag)" function.

Python 也同样支持复数,虚部由一个后缀"j"或者"J"来表示。带有非零实部的复数记为"real+imagj)",或者也可以通过"complex(real, img)"函数创建。

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

Complex numbers are always represented as two floating point numbers,the real and imaginary part. To extract these parts from a complexnumber z, use z.real and z.imag.

复数总是由实部和虚部两部分浮点数来表示。可以从 z.realz.imag 得到复数z的实部和虚部。

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

The conversion functions to floating point and integer(float(), int() and long()) don'twork for complex numbers -- there is no one correct way to convert acomplex number to a real number. Use abs(z) to get itsmagnitude (as a float) or z.real to get its real part.

用于向浮点数和整型转化的函数(float(), int() 和 long())不能对复数起作用--没有什么方法可以将复数转化为实数。可以使用abs(z)取得它的模,也可以通过z.real得到它的实部。

>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
>>>

In interactive mode, the last printed expression is assigned to thevariable _. This means that when you are using Python as adesk calculator, it is somewhat easier to continue calculations, forexample:

交互模式下,最近一次表达式输出保存在 _ 变量中。这意味着把 Python当做桌面计算器使用时,可以方便的进行连续计算,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
>>>

This variable should be treated as read-only by the user. Don'texplicitly assign a value to it -- you would create an independentlocal variable with the same name masking the built-in variable withits magic behavior.

这个变量对于用户来说是只读的。不要试图去给它赋值--限于 Python的语法规则,你只会创建一个同名的局部变量覆盖它。


3.1.2 字符串 Strings

Besides numbers, Python can also manipulate strings, which can beexpressed in several ways. They can be enclosed in single quotes ordouble quotes:

除了数值, Python还可以通过几种不同的方法操作字符串。字符串用单引号或双引号标识:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

String literals can span multiple lines in several ways. Continuationlines can be used, with a backslash as the last character on the lineindicating that the next line is a logical continuation of the line:

字符串可以通过几种方式分行。可以在行加反斜杠做为继续符,这表示下一行是当前行的逻辑沿续。

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."

print hello

Note that newlines would still need to be embedded in the string using\n; the newline following the trailing backslash isdiscarded. This example would print the following:

注意换行用 \n 来表示;反斜杠后面的新行标识(newline,缩写“n”)会转换为换行符,示例会按如下格式打印:

This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.

If we make the string literal a ``raw'' string, however, the\n sequences are not converted to newlines, but the backslashat the end of the line, and the newline character in the source, areboth included in the string as data. Thus, the example:

然而,如果我们创建一个“行”("raw")字符串,n序列就不会转为换行,源码中的反斜杠和换行符n都会做为字符串中的数据处理。如下所示:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print hello

would print:

会打印为:

This is a rather long string containing\n\
several lines of text much as you would do in C.

Or, strings can be surrounded in a pair of matching triple-quotes:""" or '''. End of lines do not need to be escapedwhen using triple-quotes, but they will be included in the string.

另外,字符串可以用一对三重引号”””或'''来标识。三重引号中的字符串在行尾不需要换行标记,所有的格式都会包括在字符串中。

print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""

produces the following output:

生成以下输出:

Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

The interpreter prints the result of string operations in the same wayas they are typed for input: inside quotes, and with quotes and otherfunny characters escaped by backslashes, to show the precisevalue. The string is enclosed in double quotes if the string containsa single quote and no double quotes, else it's enclosed in singlequotes. (The print statement, described later, can be usedto write strings without quotes or escapes.)

解释器打印出来的字符串与它们输入的形式完全相同:内部的引号,用反斜杠标识的引号和各种怪字符,都精确的显示出来。如果字符串中包含单引号,不包含双引号,可以用双引号引用它,反之可以用单引号。(后面介绍的print 语句,可以在不使用引号和反斜杠的情况下输出字符串)。

Strings can be concatenated (glued together) with the+ operator, and repeated with *:

字符串可以用 + 号联接(或者说粘合),也可以用 * 号循环。

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

Two string literals next to each other are automatically concatenated;the first line above could also have been written "word = 'Help''A'"; this only works with two literals, not with arbitrary stringexpressions:

两个字符串值之间会自动联接,上例第一行可以写成“word = 'Help' 'A'”。这种方式只对字符串值有效,任何字符串表达式都不适用这种方法。

>>> 'str' 'ing'                   #  <-  This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax

Strings can be subscripted (indexed); like in C, the first characterof a string has subscript (index) 0. There is no separate charactertype; a character is simply a string of size one. Like in Icon,substrings can be specified with the slice notation: two indicesseparated by a colon.

字符串可以用下标(索引)查询;就像 C 一样,字符串的第一个字符下标是 0。这里没有独立的字符类型,字符仅仅是大小为一的字符串。就像在 Icon 中那样,字符串的子串可以通过切片标志来表示:两个由冒号隔开的索引。

>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Slice indices have useful defaults; an omitted first index defaults tozero, an omitted second index defaults to the size of the string beingsliced.

切片索引可以使用默认值;前一个索引默认值为 0,后一个索引默认值为被切片的字符串的长度。

>>> word[:2]    # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'

Unlike a C string, Python strings cannot be changed. Assigning to anindexed position in the string results in an error:

和 C 字符串不同, Python 字符串不能改写。按字符串索引赋值会产生错误。

>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment

However, creating a new string with the combined content is easy andefficient:

然而,可以通过简单有效的组合方式生成新的字符串:

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

Here's a useful invariant of slice operations:s[:i] + s[i:] equals s.

切片操作有一个很有用的不变性:

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

Degenerate slice indices are handled gracefully: an index that is toolarge is replaced by the string size, an upper bound smaller than thelower bound returns an empty string.

退化的切片索引处理方式很优美:过大的索引代替为字符串大小,下界比上界大的返回空字符串。

>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

Indices may be negative numbers, to start counting from the right.For example:

索引可以是负数,计数从右边开始,例如:

>>> word[-1]     # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
'Hel'

But note that -0 is really the same as 0, so it does not count fromthe right!

不过需要注意的是-0还是0,它没有从右边计数!

>>> word[-0]     # (since -0 equals 0)
'H'

Out-of-range negative slice indices are truncated, but don't try thisfor single-element (non-slice) indices:

越界的负切片索引会被截断,不过不要尝试在单元素索引(非切片的)中这样做:

>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range

The best way to remember how slices work is to think of the indices aspointing between characters, with the left edge of the firstcharacter numbered 0. Then the right edge of the last character of astring of n characters has index n, for example:

理解切片的最好方式是把索引视为两个字符之间的点,第一个字符的左边是0,字符串中第n个字符的右边是索引n,例如:

 +---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0...5 inthe string; the second row gives the corresponding negative indices.The slice from i to j consists of all characters betweenthe edges labeled i and j, respectively.

第一行是字符串中给定的0到5各个索引的位置,第二行是对应的负索引。从i到j的切片由这两个标志之间的字符组成。

For non-negative indices, the length of a slice is the difference ofthe indices, if both are within bounds. For example, the length ofword[1:3] is 2.

对于非负索引,切片长度就是两索引的差。例如,word[1:3]的长度是2。

The built-in function len() returns the length of a string:

内置函数 len() 返回字符串长度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

See Also:

Sequence Types
Strings, and the Unicode strings described in the next section, are examples of sequence types, and support the common operations supported by such types.
String Methods
Both strings and Unicode strings support a large number of methods for basic transformations and searching.
String Formatting Operations
The formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.


3.1.3 Unicode 字符串 Unicode Strings

Starting with Python 2.0 a new data type for storing text data isavailable to the programmer: the Unicode object. It can be used tostore and manipulate Unicode data (see http://www.unicode.org/)and integrates well with the existing string objects providingauto-conversions where necessary.

从Python2.0开始,程序员们可以使用一种新的数据类型来存储文本数据:Unicode 对象。它可以用于存储多种Unicode数据(请参阅http://www.unicode.org/ ),并且,通过必要时的自动转换,它可以与现有的字符串对象良好的结合。

Unicode has the advantage of providing one ordinal for every characterin every script used in modern and ancient texts. Previously, therewere only 256 possible ordinals for script characters and texts weretypically bound to a code page which mapped the ordinals to scriptcharacters. This lead to very much confusion especially with respectto internationalization (usually written as "i18n" --"i" + 18 characters + "n") of software. Unicodesolves these problems by defining one code page for all scripts.

Unicode针对现代和旧式的文本中所有的字符提供了一个序列。以前,字符只能使用256个序号,文本通常通过绑定代码页来与字符映射。这很容易导致混乱,特别是软件的国际化( internationalization --通常写做“i18n”--“i”+ "i" +“n”)。 Unicode 通过为所有字符定义一个统一的代码页解决了这个问题。

Creating Unicode strings in Python is just as simple as creatingnormal strings:

Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单:

>>> u'Hello World !'
u'Hello World !'

The small "u" in front of the quote indicates that anUnicode string is supposed to be created. If you want to includespecial characters in the string, you can do so by using the PythonUnicode-Escape encoding. The following example shows how:

引号前小写的“u”表示这里创建的是一个 Unicode字符串。如果你想加入一个特殊字符,可以使用 Python 的Unicode-Escape 编码。如下例所示:

>>> u'Hello\u0020World !'
u'Hello World !'

The escape sequence \u0020 indicates to insert the Unicodecharacter with the ordinal value 0x0020 (the space character) at thegiven position.

被替换的 \u0020 标识表示在给定位置插入编码值为 0x0020 的Unicode 字符(空格符)。

Other characters are interpreted by using their respective ordinalvalues directly as Unicode ordinals. If you have literal stringsin the standard Latin-1 encoding that is used in many Western countries,you will find it convenient that the lower 256 charactersof Unicode are the same as the 256 characters of Latin-1.

其它字符也会被直接解释成对应的 Unicode码。如果你有一个在西方国家常用的 Latin-1 编码字符串,你可以发现Unicode 字符集的前256个字符与 Latin-1 的对应字符编码完全相同。

For experts, there is also a raw mode just like the one for normalstrings. You have to prefix the opening quote with 'ur' to havePython use the Raw-Unicode-Escape encoding. It will only applythe above \uXXXX conversion if there is an uneven number ofbackslashes in front of the small 'u'.

另外,有一种与普通字符串相同的行模式。要使用 Python 的 Raw-Unicode-Escape 编码,你需要在字符串的引号前加上 ur前缀。如果在小写“u”前有不止一个反斜杠,它只会把那些单独的
uXXXX 转化为Unicode字符。

>>> ur'Hello\u0020World !'
u'Hello World !'
>>> ur'Hello\u0020World !'
u'Hello\\u0020World !'

The raw mode is most useful when you have to enter lots ofbackslashes, as can be necessary in regular expressions.

行模式在你需要输入很多个反斜杠时很有用,使用正则表达式时会带来方便。

Apart from these standard encodings, Python provides a whole set ofother ways of creating Unicode strings on the basis of a knownencoding.

作为这些编码标准的一部分, Python 提供了一个完备的方法集用于从已知的编码集创建 Unicode 字符串。

The built-in function unicode() providesaccess to all registered Unicode codecs (COders and DECoders). Some ofthe more well known encodings which these codecs can convert areLatin-1, ASCII, UTF-8, and UTF-16.The latter two are variable-length encodings that store each Unicodecharacter in one or more bytes. The default encoding isnormally set to ASCII, which passes through characters in the range0 to 127 and rejects any other characters with an error.When a Unicode string is printed, written to a file, or convertedwith str(), conversion takes place using this default encoding.

内置函数 unicode() 提供了访问(编码和解码)所有已注册的 Unicode 编码的方法。它能转换众所周知的Latin-1, ASCII, UTF-8, 和UTF-16。后面的两个可变长编码字符集用一个或多个 byte 存储 Unicode 字符。默认的字符集是ASCII,它只处理0到127的编码,拒绝其它的字符并返回一个错误。当一个 Unicode 字符串被打印、写入文件或通过 str()转化时,它们被替换为默认的编码。

>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u"漩?"
u'\xe4\xf6\xfc'
>>> str(u"漩?")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

To convert a Unicode string into an 8-bit string using a specificencoding, Unicode objects provide an encode() methodthat takes one argument, the name of the encoding. Lowercase namesfor encodings are preferred.

要把一个 Unicode 字符串用指定的字符集转化成8位字符串,可以使用 Unicode 对象提供的 encode() 方法,它有一个参数用以指定编码名称。编码名称小写。

>>> u"漩?".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

If you have data in a specific encoding and want to produce acorresponding Unicode string from it, you can use theunicode() function with the encoding name as the secondargument.

如果你有一个特定编码的字符串,想要把它转为 Unicode字符集,,可以使用 encode() 函数,它以编码名做为第二个参数。

>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'


3.1.4 链表 Lists

Python knows a number of compound data types, used to grouptogether other values. The most versatile is the list, whichcan be written as a list of comma-separated values (items) betweensquare brackets. List items need not all have the same type.

Python 已经有了几个复合数据类型,用于组织其它的值。最通用的是链表,它写为中括之间用逗号分隔的一列值(子项),链表的子项不一定是同一类型的值。

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]

Like string indices, list indices start at 0, and lists can be sliced,concatenated and so on:

像字符串一样,链表也以零开始,可以被切片,联接,等等:

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']

Unlike strings, which are immutable, it is possible to changeindividual elements of a list:

与不变的字符串不同,链表可以改变每个独立元素的值:

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

Assignment to slices is also possible, and this can even change the sizeof the list:

可以进行切片操作,甚至还可以改变链表的大小:

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

The built-in function len() also applies to lists:

内置函数len()也同样可以用于链表:

>>> len(a)
8

It is possible to nest lists (create lists containing other lists),for example:

它也可以嵌套链表(在链表中创建其它链表),例如:

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

Note that in the last example, p[1] and q really refer tothe same object! We'll come back to object semantics later.

注意最后一个例子, p[1]q 实际上指向同一个对象!我们在后面会讲到对象语法。


3.2 开始编程 First Steps Towards Programming

Of course, we can use Python for more complicated tasks than addingtwo and two together. For instance, we can write an initialsub-sequence of the Fibonacci series as follows:

当然,我们可以用 Python做比2加2更复杂的事。例如,我们可以用以下的方法输出菲波那契(Fibonacci)序列的子序列:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8

This example introduces several new features.

示例中介绍了一些新功能:

  • The first line contains a multiple assignment: the variablesa and b simultaneously get the new values 0 and 1. On thelast line this is used again, demonstrating that the expressions onthe right-hand side are all evaluated first before any of theassignments take place. The right-hand side expressions are evaluatedfrom the left to the right.

    第一行包括了 复合参数:变量 ab 同时被赋值为 0 和 1 。最后一行又一次使用了这种技术,证明了在赋值之前表达式右边先进行了运算。右边的表达式从左到右运算。

  • The while loop executes as long as the condition (here:b < 10) remains true. In Python, like in C, any non-zerointeger value is true; zero is false. The condition may also be astring or list value, in fact any sequence; anything with a non-zerolength is true, empty sequences are false. The test used in theexample is a simple comparison. The standard comparison operators arewritten the same as in C: < (less than), > (greater than),== (equal to), <= (less than or equal to),>= (greater than or equal to) and <

 
 
标签: Tutorial , Python 打印本文
 
 
  相关资讯
RSS
 
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站