中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > C/C++
Python Tutorial(1)
作者:未知 时间:2005-09-13 23:28 出处:Blog.ChinaUnix.net 责编:chinaitpower
              摘要:Python Tutorial(1)
python2.4的一个教程

前言 Front Matter

ALT=

Abstract:

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

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

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, http://www.python.org/, and can be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.

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

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

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

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

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

For a description of standard objects and modules, see the Python Library Reference document. The Python Reference Manual gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and Python/C API Reference. There are also several books covering Python in depth.

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

This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. Instead, it introduces many of Python's most noteworthy features, and will give you a good idea of the language's flavor and style. After reading it, you will be able to read and write Python modules and programs, and you will be ready to learn more about the various Python library modules described in the Python Library Reference.

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

1. 开胃菜 Whetting Your Appetite

If you ever wrote a large shell script, you probably know this feeling: you'd love to add yet another feature, but it's already so slow, and so big, and so complicated; or the feature involves a system call or other function that is only accessible from C ...Usually the problem at hand isn't serious enough to warrant rewriting the script in C; perhaps the problem requires variable-length strings or other data types (like sorted lists of file names) that are easy in the shell but lots of work to implement in C, or perhaps you're not sufficiently familiar with C.

如果你写过大规模的 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. You need to develop software more quickly. Possibly perhaps you've written a program that could use an extension language, and you don't want to design a language, write and debug an interpreter for it, then tie it into your application.

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

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

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

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

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

Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary. The interpreter can be used interactively, which makes it easy to experiment with features of the language, to write throw-away programs, 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. Programs written in Python are typically much shorter than equivalent C or C++ programs, for several reasons: Python 可以写出很紧凑和可读性很强的程序。用 Python 写的程序通常比同样的 C 或 C++ 程序要短得多,这是因为以下几个原因:

  • the high-level data types allow you to express complex operations in a single statement;
  • statement grouping is done by indentation instead of beginning and ending brackets;
  • no variable or argument declarations are necessary.

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

Python is extensible: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and 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 ``Monty Python's Flying Circus'' and has nothing to do with nasty reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged!

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

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

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

In the next chapter, the mechanics of using the interpreter are explained. This is rather mundane information, but essential for trying out the examples shown later.

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

The rest of the tutorial introduces various features of the Python language and system through examples, beginning with simple expressions, statements and data types, through functions and modules, and finally touching upon advanced concepts like exceptions and 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 is available; putting /usr/local/bin in your Unix shell's search 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 the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)

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

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

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

The interpreter's line-editing features usually aren't very sophisticated. On Unix, whoever installed the interpreter may have enabled support for the GNU readline library, which adds more elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix for an introduction to the keys. If nothing appears to happen, or if P is echoed, command line editing isn't available; you'll only be able to use backspace to remove characters from the current line.

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

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

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

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

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

Note that there is a difference between "python file" and "python <file". In the latter case, input requests from the program, such as calls to input() and raw_input(), are satisfied from file. Since this file has already been read until the end by the parser before the program starts executing, the program will encounter end-of-file immediately. In the former case (which is usually what you want) they are satisfied from whatever file or 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 to run the script and enter interactive mode afterwards. This can be done by passing -i before the script. (This does not work if the script is read from standard input, for the same reason as explained in the previous paragraph.)

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


2.1.1 参数传递 Argument Passing

When known to the interpreter, the script name and additional arguments thereafter are passed to the script in the variable sys.argv, which is a list of strings. Its length is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. Options found after -c command are not consumed by the Python interpreter's option processing but left in sys.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 be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (">>"); for continuation lines it prompts with the secondary prompt, by default three dots ("... "). The interpreter prints a welcome message stating its version number 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 error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from the executed commands is written to standard output.

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

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

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


2.2.2 执行Python脚本 Executable Python Scripts

On BSD'ish Unix systems, Python scripts can be made directly executable, 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) at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python.

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

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

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

$ chmod +x myscript.py

2.2.3 源程序编码 Source Code Encoding

It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right 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 as iso-8859-1, and it will be possible to directly write Unicode string literals in the selected encoding. The list of possible encodings can be found in the Python Library Reference, in the section on codecs.

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

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

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

By using UTF-8 (either through the signature or an encoding declaration), characters of most languages in the world can be used simultaneously in string literals and comments. Using non-ASCIIcharacters in identifiers is not supported. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters 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 some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.

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

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

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

If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like "if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')". If you want to use the startup file in a script, 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 the presence or absence of prompts (">>" and "... "): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you 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 the interactive prompt, include comments. Comments in Python start with the hash character, "#", and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character 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 wait for the primary prompt, ">>". (It shouldn't take long.)

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


3.1.1 数值 Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or 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 a variable. 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 type operands 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 with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be 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 complex number 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't work for complex numbers -- there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (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 the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

交互模式下,最近一次表达式输出保存在 _ 变量中。这意味着把 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't explicitly assign a value to it -- you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

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


3.1.2 字符串 Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double 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. Continuation lines can be used, with a backslash as the last character on the line indicating 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 is discarded. 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 backslash at the end of the line, and the newline character in the source, are both 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 escaped when 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 way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it's enclosed in single quotes. (The print statement, described later, can be used to 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 string expressions:

两个字符串值之间会自动联接,上例第一行可以写成“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 character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated 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 to zero, an omitted second index defaults to the size of the string being sliced.

切片索引可以使用默认值;前一个索引默认值为 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 an indexed 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 and efficient:

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

>>> '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 too large is replaced by the string size, an upper bound smaller than the lower 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 from the right!

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

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

Out-of-range negative slice indices are truncated, but don't try this for 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 as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string 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 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

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

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[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 is available to the programmer: the Unicode object. It can be used to store and manipulate Unicode data (see http://www.unicode.org/) and integrates well with the existing string objects providing auto-conversions where necessary.

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

Unicode has the advantage of providing one ordinal for every character in every script used in modern and ancient texts. Previously, there were only 256 possible ordinals for script characters and texts were typically bound to a code page which mapped the ordinals to script characters. This lead to very much confusion especially with respect to internationalization (usually written as "i18n" -- "i" + 18 characters + "n") of software. Unicode solves 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 creating normal strings:

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

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

The small "u" in front of the quote indicates that an Unicode string is supposed to be created. If you want to include special characters in the string, you can do so by using the Python Unicode-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 Unicode character with the ordinal value 0x0020 (the space character) at the given position.

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

Other characters are interpreted by using their respective ordinal values directly as Unicode ordinals. If you have literal strings in the standard Latin-1 encoding that is used in many Western countries, you will find it convenient that the lower 256 characters of 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 normal strings. You have to prefix the opening quote with 'ur' to have Python use the Raw-Unicode-Escape encoding. It will only apply the above \uXXXX conversion if there is an uneven number of backslashes 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 of backslashes, as can be necessary in regular expressions.

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

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

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

The built-in function unicode() provides access to all registered Unicode codecs (COders and DECoders). Some of the more well known encodings which these codecs can convert are Latin-1, ASCII, UTF-8, and UTF-16. The latter two are variable-length encodings that store each Unicode character in one or more bytes. The default encoding is normally set to ASCII, which passes through characters in the range 0 to 127 and rejects any other characters with an error. When a Unicode string is printed, written to a file, or converted with 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 specific encoding, Unicode objects provide an encode() method that takes one argument, the name of the encoding. Lowercase names for 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 a corresponding Unicode string from it, you can use the unicode() function with the encoding name as the second argument.

如果你有一个特定编码的字符串,想要把它转为 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 group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square 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 change individual 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 size of 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 to the 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 adding two and two together. For instance, we can write an initial sub-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 variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from 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-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and <
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有