3. An Informal Introduction to Python

在以下示例中,输入和输出以提示符(>>>...)的出现和消失来标注:如果想要重现示例,提示符出现时,必须输入提示符之后的所有内容。不以提示符开头的行是解释器的输出。需要注意的是示例中行内从属提示符意味着必须多输入一个空行,用来终止多行命令。

手册中的许多示例,包括以交互提示符输入的,都包含注释。Python的注释以#字符开头,直至物理行尾结束。注释可以出现在行首,或者跟在空白符或代码后面,但是不能出现在字符串中。字符串中的#字符仅仅是#字符。由于注释是用来阐述代码的,并不被Python所解释,重写示例时可以忽略它们。

一些示例:

  1. # this is the first comment
  2. spam = 1 # and this is the second comment
  3. # ... and now a third!
  4. text = "# This is not a comment because it's inside quotes."

3.1 Using Python as a Calculator

尝试一些简单的Python命令。启动解释器并等待主提示符>>>出现。(不会等待太久)

3.1.1 Numbers

解释器可以作为简单计算器使用:在解释器中输入表达式,解释器会输出值。表达式语法很简单:操作符+, - * /跟其他语言意义一样(如C跟Pascal);括号(())用于分组。例如:

  1. >>> 2 + 2
  2. 4
  3. >>> 50 - 5*6
  4. 20
  5. >>> (50 - 5*6) / 4
  6. 5.0
  7. >>> 8 / 5 # division always returns a floating point number
  8. 1.6

整数(如2, 4, 20)类型是int,带有小数的数(如5.0, 1.6)类型是float。后面会有更多关于数字类型的介绍。

除(/)总是返回浮点数。操作符//是向下取整除法,返回一个整数结果(舍弃小数部分结果),操作符%用于求余数:

  1. >>> 17 / 3 # classic division returns a float
  2. 5.666666666666667
  3. >>>
  4. >>> 17 // 3 # floor division discards the fractional part
  5. 5
  6. >>> 17 % 3 # the % operator returns the remainder of the division
  7. 2
  8. >>> 5 * 3 + 2 # result * divisor + remainder
  9. 17

Python中可以使用操作符**计算幂[1]

  1. >>> 5 ** 2 # 5 squared
  2. 25
  3. >>> 2 ** 7 # 2 to the power of 7
  4. 128

等号(=)用于将值赋给变量。赋值操作之后,在下一个交互提示符之前不会有任何输出:

  1. >>> width = 20
  2. >>> height = 5 * 9
  3. >>> width * height
  4. 900

如果变量没有定义(没有被赋值),尝试使用会得到一个错误:

  1. >>> n # try to access an undefined variable
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name 'n' is not defined

Python提供了浮点数的完整支持;在复合类型操作中,整型会被提升为浮点型:

  1. >>> 4 * 3.75 - 1
  2. 14.0

交互模式中,最后打印的表达式会被赋值给变量_。意味着Python作为桌面计算器使用时,易于连续计算。例如:

  1. >>> tax = 12.5 / 100
  2. >>> price = 100.50
  3. >>> price * tax
  4. 12.5625
  5. >>> price + _
  6. 113.0625
  7. >>> round(_, 2)
  8. 113.06

该变量对于用户应该被当做只读的。不要对其显式赋值——否则将会创建同名的独立局部变量,该变量屏蔽内建变量的魔法效果。

intfloat之外,Python也支持其他数字类型,比如DecimalFraction。Python也有对复数(complex numbers)的内建支持,使用j或者J标识复数的虚部(如3+5j)。

3.1.2 Strings

除了数字,Python也提供了多种表示字符串的方式。字符串可以使用单引号('...')或者双引号(“...”)围起来,效果是一样的[2]\用于转义:

  1. >>> 'spam eggs' # single quotes
  2. 'spam eggs'
  3. >>> 'doesn\'t' # use \' to escape the single quote...
  4. "doesn't"
  5. >>> "doesn't" # ...or use double quotes instead
  6. "doesn't"
  7. >>> '"Yes," he said.'
  8. '"Yes," he said.'
  9. >>> "\"Yes,\" he said."
  10. '"Yes," he said.'
  11. >>> '"Isn\'t," she said.'
  12. '"Isn\'t," she said.'

交互式解释器中,输出字符串被引号包围,特俗字符使用反斜杠转义。虽然字符串在输入时可能看起来不一样(包围字符串的引号可以不同),但是两种形式的字符串是相等的。当字符串包含单引号并且不包含双引号时,可以使用双引号包围,反之则使用单引号。print()函数会省略外围引号,打印转义字符和特殊字符,使得输出更加可读:

  1. >>> '"Isn\'t," she said.'
  2. '"Isn\'t," she said.'
  3. >>> print('"Isn\'t," she said.')
  4. "Isn't," she said.
  5. >>> s = 'First line.\nSecond line.' # \n means newline
  6. >>> s # without print(), \n is included in the output
  7. 'First line.\nSecond line.'
  8. >>> print(s) # with print(), \n produces a new line
  9. First line.
  10. Second line.

如果不希望以\开头的字符被解释为转义字符,可以使用原生字符串,在第一个引号前加r即可:

  1. >>> print('C:\some\name') # here \n means newline!
  2. C:\some
  3. ame
  4. >>> print(r'C:\some\name') # note the r before the quote
  5. C:\some\name

字符串字面常量可以跨越多行。方式之一是使用多行引用:"""..."""或者'''...'''。换行符会自动包括到字符串中,但是可以在行末添加\阻止其发生。如下示例:

  1. print("""\
  2. Usage: thingy [OPTIONS]
  3. -h Display this usage message
  4. -H hostname Hostname to connect to
  5. """)

产生如下输出(注意首行并没有包括在内):

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

字符串可以使用操作符+串联起来,使用操作符*使其重复:

  1. >>> # 3 times 'un', followed by 'ium'
  2. >>> 3 * 'un' + 'ium'
  3. 'unununium'

两个或者更多相邻的字符串字面常量会自动拼接起来:

  1. >>> 'Py' 'thon'
  2. 'Python'

以上只对只有字符串字面常量有效,对变量或者表达式无效:

  1. >>> prefix = 'Py'
  2. >>> prefix 'thon' # can't concatenate a variable and a string literal
  3. ...
  4. SyntaxError: invalid syntax
  5. >>> ('un' * 3) 'ium'
  6. ...
  7. SyntaxError: invalid syntax

如果希望拼接变量或者变量以及字面常量,使用+:

  1. >>> prefix + 'thon'
  2. 'Python'

如果希望分割长字符串,这个功能特别有用:

  1. >>> text = ('Put several strings within parentheses '
  2. ... 'to have them joined together.')
  3. >>> text
  4. 'Put several strings within parentheses to have them joined together.'

字符串支持索引操作,第一个字符串索引为0。Python中没有单独的字符类型;一个字符仅仅是长度为1的字符串:

  1. >>> word = 'Python'
  2. >>> word[0] # character in position 0
  3. 'P'
  4. >>> word[5] # character in position 5
  5. 'n'

从右计数时,索引也可以是负数:

  1. >>> word[-1] # last character
  2. 'n'
  3. >>> word[-2] # second-last character
  4. 'o'
  5. >>> word[-6]
  6. 'P'

注意由于-0与0相同,所以负数索引从-1开始。

除了索引,字符串也支持切片。使用索引获得个别字符,使用切片获取字符子串:

  1. >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
  2. 'Py'
  3. >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
  4. 'tho'

注意切片操作的返回值包含起始索引,不包含结束索引。使得s[:i] + s[:i]总是等于s

  1. >>> word[:2] + word[2:]
  2. 'Python'
  3. >>> word[:4] + word[4:]
  4. 'Python'

切片操作指定了非常有用的默认值;省略第一个索引默认为0,省略第二个索引默认当前切片字符串长度。

  1. >>> word[:2] # character from the beginning to position 2 (excluded)
  2. 'Py'
  3. >>> word[4:] # characters from position 4 (included) to the end
  4. 'on'
  5. >>> word[-2:] # characters from the second-last (included) to the end
  6. 'on'

一种记住切片工作方式的方法是:把索引当做字符之间的指向,左边第一个字符的边编号0。长度为n的字符串最后一个字符的右边索引为n

  1. +---+---+---+---+---+---+
  2. | P | y | t | h | o | n |
  3. +---+---+---+---+---+---+
  4. 0 1 2 3 4 5 6
  5. -6 -5 -4 -3 -2 -1

第一行数据给出了字符串索引0...6的位置;第二行数字给出了其对应负索引。从ij的切片包含边i和边j之间所有的字符。

对于非负索引,如果两个索引都在界限内,切片长度是索引之差。例如,word[1:3]的长度为2.

使用超过界限的索引会抛出异常:

  1. >>> word[42] # the word only has 6 characters
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. IndexError: string index out of range

然而,切片操作时超出界限的切片索引会被优雅处理:

  1. >>> word[4:42]
  2. 'on'
  3. >>> word[42:]
  4. ''

Python字符串不能被改变——他们是不可变的。因此,企图对字符串索引位置赋值会抛出异常:

  1. >>> word[0] = 'J'
  2. ...
  3. TypeError: 'str' object does not support item assignment
  4. >>> word[2:] = 'py'
  5. ...
  6. TypeError: 'str' object does not support item assignment

如果需要不同的字符串,应该新建一个:

  1. >>> 'J' + word[1:]
  2. 'Jython'
  3. >>> word[:2] + 'py'
  4. 'Pypy'

built-in函数len()返回字符串长度:

  1. >>> s = 'supercalifragilisticexpialidocious'
  2. >>> len(s)
  3. 34

参见:

Text Sequence Type — str

字符串是序列的一种,支持序列所支持的一般操作。

String Methods

字符串支持大量基础转换和搜索的方法

Formatted string literals

字符串字面常量拥有嵌入式表达式

Format String Syntax

使用str.format()格式化字符串的相关信息

printf-style String Formatting

详细描述了使用%格式化字符串的旧字符串格式化操作

3.1.3 Lists

Python支持许多用来组织其他值的复合数据类型。最通用的是列表,包含在中括号中,以逗号分隔的一列值(项)就是列表。列表可以包含不同类型的数据,但在使用时通常包含相同类型数据。

  1. >>> squares = [1, 4, 9, 16, 25]
  2. >>> squares
  3. [1, 4, 9, 16, 25]

与字符串相似(与其他所有buit-in序列类型相似),列表支持索引和切片操作:

  1. >>> squares[0] # indexing returns the item
  2. 1
  3. >>> squares[-1]
  4. 25
  5. >>> squares[-3:] # slicing returns a new list
  6. [9, 16, 25]

所有的切片操作返回包含请求元素的新列表。这意味着下列切片操作返回对列表的浅复制:

  1. >>> squares[:]
  2. [1, 4, 9, 16, 25]

列表也支持拼接操作:

  1. >>> squares + [36, 49, 64, 81, 100]
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

与字符串的不可变不同,列表是可变类型。支持改变列表内容的操作:

  1. >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
  2. >>> 4 ** 3 # the cube of 4 is 64, not 65!
  3. 64
  4. >>> cubes[3] = 64 # replace the wrong value
  5. >>> cubes
  6. [1, 8, 27, 64, 125]

使用append()方法可以在列表末尾加入新项(后面会详细讨论):

  1. >>> cubes.append(216) # add the cube of 6
  2. >>> cubes.append(7 ** 3) # and the cube of 7
  3. >>> cubes
  4. [1, 8, 27, 64, 125, 216, 343]

对切片赋值也是可行的,这种操作可以改变列表的大小或者完全清除列表:

  1. >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  2. >>> letters
  3. ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  4. >>> # replace some values
  5. >>> letters[2:5] = ['C', 'D', 'E']
  6. >>> letters
  7. ['a', 'b', 'C', 'D', 'E', 'f', 'g']
  8. >>> # now remove them
  9. >>> letters[2:5] = []
  10. >>> letters
  11. ['a', 'b', 'f', 'g']
  12. >>> # clear the list by replacing all the elements with an empty list
  13. >>> letters[:] = []
  14. >>> letters
  15. []

built-in函数len()也可以应用于列表:

  1. >>> letters = ['a', 'b', 'c', 'd']
  2. >>> len(letters)
  3. 4

也支持嵌套列表(包含其他列表的列表),例如:

  1. >>> a = ['a', 'b', 'c']
  2. >>> n = [1, 2, 3]
  3. >>> x = [a, n]
  4. >>> x
  5. [['a', 'b', 'c'], [1, 2, 3]]
  6. >>> x[0]
  7. ['a', 'b', 'c']
  8. >>> x[0][1]
  9. 'b'

3.2 First Steps Towards Programming

当然,可以使用Python完成比2+2更加复杂的任务。例如,可以写一段生成斐波那契数列的代码:

  1. >>> # Fibonacci series:
  2. ... # the sum of two elements defines the next
  3. ... a, b = 0, 1
  4. >>> while b < 10:
  5. ... print(b)
  6. ... a, b = b, a+b
  7. ...
  8. 1
  9. 1
  10. 2
  11. 3
  12. 5
  13. 8

以上示例介绍了几个新特性:

  • 第一行包含了多重赋值:变量ab同时得到值0和1。最后一行再次使用多重赋值,证明了在右边的所有表达式在赋值操作发生之前首先计算值。右边的表达式从左到右计算值。
  • 只要条件(这里是b < 10)为true,while循环就会执行。Python中,与C相似,任何非零整数值都是true;零是false。条件也可以是字符串或者列表,事实上可以是任何序列;非零长度序列是true,空序列是false。示例中使用的测试是一个简单的比较。标准的比较操作符与C相同:< (小于),>(大于), ==(等于), <= (小于等于), >=(大于等于)以及 !=(不等于)。
  • 缩进了循环体:缩进是Python聚合语句的方式。在交互模式中,必须输入tab或者几个空格来缩进每一行。实践中,可以使用文本编辑器来准备更加复杂的输入;所有好用的文本编辑器都提供了自动缩进功能。交互模式中输入复杂语句后,必须输入空行来指示输入完成(因为解释器无法判断输入的最后一行)。记住在同一基础块中的每一行语句必须缩进相同的数量。
  • print()函数输出参数的值。不同于输出想要输出的表达式(就像上述计算器示例中那样),该函数可以处理多个参数,浮点数以及字符串。输出的字符串没有引号包围,多个参数之间会插入空格。因此可以使用其优雅地格式化输出,如下示例:
  1. >>> i = 256*256
  2. >>> print('The value of i is', i)
  3. The value of i is 65536

关键字参数end可以用来避免输出中的换行,或者使用不同的字符串结束输出:

  1. >>> a, b = 0, 1
  2. >>> while b < 1000:
  3. ... print(b, end=',')
  4. ... a, b = b, a+b
  5. ...
  6. 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

Footnotes

[1] 由于**-拥有更高的优先级,-3**2会被解释为-(3**2)并且结果是-9。如要避免优先级问题而得到结果9,可以使用(-3) ** 2

[2] 与其他语言不同,特殊字符如\n在单引号('...')和双引号("...")意义相同。不同之处在于在单引号之中不需要转义双引号",但是需要转义单引号\',反之亦然。

[译]The Python Tutorial#3. An Informal Introduction to Python的更多相关文章

  1. Python Tutorial 学习(三)--An Informal Introduction to Python

    3.1. 将Python用作计算器 3.1.1. Numbers 数 作为一个计算器,python支持简单的操作, '+','-','*','/'地球人都知道的加减乘除. ()可以用来改变优先级,同数 ...

  2. [译]The Python Tutorial#6. Modules

    [译]The Python Tutorial#Modules 6. Modules 如果你从Python解释器中退出然后重新进入,之前定义的名字(函数和变量)都丢失了.因此,如果你想写长一点的程序,使 ...

  3. Python Tutorial笔记

    Python Tutorial笔记 Python入门指南 中文版及官方英文链接: Python入门指南 (3.5.2) http://www.pythondoc.com/pythontutorial3 ...

  4. 2018-06-20 中文代码示例视频演示Python入门教程第三章 简介Python

    知乎原链 Python 3.6.5官方入门教程中示例代码汉化后演示 对应在线文档: 3. An Informal Introduction to Python 不知如何合集, 请指教. 中文代码示例P ...

  5. [译]The Python Tutorial#12. Virtual Environments and Packages

    [译]The Python Tutorial#Virtual Environments and Packages 12.1 Introduction Python应用经常使用不属于标准库的包和模块.应 ...

  6. [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II

    [译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...

  7. [译]The Python Tutorial#10. Brief Tour of the Standard Library

    [译]The Python Tutorial#Brief Tour of the Standard Library 10.1 Operating System Interface os模块为与操作系统 ...

  8. [译]The Python Tutorial#2. Using the Python Interpreter

    [译]The Python Tutorial#Using the Python Interpreter 2.1 Invoking the Interpreter Python解释器通常安装在目标机器的 ...

  9. [译]The Python Tutorial#1. Whetting Your Appetite

    [译]The Python Tutorial#Whetting Your Appetite 1. Whetting Your Appetite 如果你需要使用计算机做很多工作,最终会发现很多任务需要自 ...

随机推荐

  1. 【密码学】SSL双向认证以及证书的制作和使用

    客户端认证服务器: 正规的做法是:到国际知名的证书颁发机构,如VeriSign申请一本服务器证书,比如支付宝的首页,点击小锁的图标,可以看到支付宝是通过VeriSign认证颁发的服务器证书: 我们用的 ...

  2. 【JavaEE】Web Service 的工作原理

    Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的 ...

  3. Oracle同义词。。。

    同义词 --私有同义词--私有同义词权限grant create synonym to scott;--创建私有同义词create synonym dp for scott.dept;--将查询dep ...

  4. Xcode8-beat升级需谨慎

    Xcode8-beat版本在打开xib文件的时候,出现了如下的弹窗 在这里要选择Cancel,选择Choose后xib文件的verson会改变,那么Xcode7就没法打开了(坑队友啦), 更没法运行 ...

  5. mybatis批量插入插入数据、批量条件查询

    ps:参考文章连接:https://www.cnblogs.com/admol/articles/4248159.html 关于个人的使用经验:先把数据放到bean中,多个的话就全放入list集合,如 ...

  6. spring的工厂方法

    http://blog.csdn.net/nvd11/article/details/51542360

  7. IOS 自定义Layer(图层)

    方式1: @interface NJViewController () @end @implementation NJViewController - (void)viewDidLoad { [sup ...

  8. World Wind Java开发之十四——添加WMS地图服务资源(转)

    数据是GIS的核心,没有数据一切无从谈起,Internet上有很多在线WMS地图服务资源,我们可以好好利用这些数据资源,比如天地图.必应地图.NASA.OGC数据服务等等. 在我们国家常用的还是天地图 ...

  9. World Wind Java开发之六——解析shape文件(转)

    http://blog.csdn.net/giser_whu/article/details/41647117 最近一直忙于导师项目的事情了,几天没更新了,昨天和今天研究了下WWJ解析shp文件的源代 ...

  10. go语言,爬取百度贴吧指定贴所有内容

    初级爬虫,为了学习一下常用的goquery. goquery 配置 go get https://github.com/PuerkitoBio/goquery 会提示不支持https方式 解决方案: ...