3. Python 的非正式介绍

在以下示例中,Importing 和输出pass是否存在提示(>>>)来区分:要重复该示例,必须在提示出现后键入所有内容;从解释器输出不以提示开头的行。请注意,在示例中,仅在一行上出现辅助提示意味着您必须键入一个空行。这用于结束多行命令。

本手册中的许多示例,甚至是在交互式提示下 Importing 的示例,都包含 Comments。 Python 中的 Comments 以井号#开始,并延伸到物理行的末尾。Comments 可能会出现在行的开头或空格或代码之后,但不能出现在字符串 Literals 中。字符串 Literals 中的哈希字符只是哈希字符。由于 Comments 是为了澄清代码,而不是由 Python 解释,因此在键入示例时可以将其Ellipsis。

Some examples:

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

3.1. 使用 Python 作为计算器

让我们try一些简单的 Python 命令。启动解释器并 await 主要提示>>>。 (不应该花很长时间.)

3.1.1. Numbers

解释器就像一个简单的计算器:您可以在其中键入一个表达式,然后它将写入该值。表达式语法很简单:运算符+-*/的工作方式与大多数其他语言(例如 Pascal 或 C)一样;括号(())可用于分组。例如:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5.0*6) / 4
5.0
>>> 8 / 5.0
1.6

整数(例如2420)的类型为int,带小数部分的整数(例如5.01.6)的类型为float。在本教程的后面,我们将看到更多有关数字类型的信息。

除法(/)操作的返回类型取决于其操作数。如果两个操作数的类型均为int,则执行floor division并返回int。如果任何一个操作数是float,则执行经典除法并返回float//运算符也可用于进行地板分割,无论操作数是什么。余数可以使用%运算符计算:

>>> 17 / 3  # int / int -> int
5
>>> 17 / 3.0  # int / float -> float
5.666666666666667
>>> 17 // 3.0  # explicit floor division discards the fractional part
5.0
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

使用 Python,可以使用**运算符来计算[1]的幂:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

等号(=)用于为变量分配值。之后,在下一个交互式提示之前不会显示任何结果:

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

如果未“定义”变量(为变量分配值),则try使用它会给您一个错误:

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

完全支持浮点;混合类型操作数的运算符将整数操作数转换为浮点数:

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

在交互模式下,最后打印的表达式被分配给变量_。这意味着当您将 Python 用作桌面计算器时,continue 进行计算会更容易一些,例如:

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

用户应将此变量视为只读。不要显式地给它赋值-您将创建一个具有相同名称的独立局部变量,以其内置的魔术行为掩盖内置变量。

除了intfloat,Python 还支持其他类型的数字,例如DecimalFraction。 Python 还具有对complex numbers的内置支持,并使用jJ后缀指示虚部(例如3+5j)。

3.1.2. Strings

除数字外,Python 还可以操纵字符串,该字符串可以pass多种方式表示。它们可以用单引号('...')或双引号("...")括起来,结果相同[2]\可用于转义引号:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

在交互式解释器中,输出字符串用引号引起来,特殊字符用反斜杠转义。尽管有时这看起来可能与 Importing 有所不同(括起来的引号可能会更改),但这两个字符串是等效的。如果字符串包含单引号而不包含双引号,则将字符串括在双引号中;否则,将其括在单引号中。 print语句passEllipsis引号并打印转义的和特殊字符来产生更可读的输出:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print '"Isn\'t," they said.'
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print, \n is included in the output
'First line.\nSecond line.'
>>> print s  # with print, \n produces a new line
First line.
Second line.

如果您不希望将\开头的字符解释为特殊字符,则可以使用原始字符串,方法是在第一引号之前添加r

>>> print 'C:\some\name'  # here \n means newline!
C:\some
ame
>>> print r'C:\some\name'  # note the r before the quote
C:\some\name

字符串 Literals 可以跨越多行。一种方法是使用三引号:"""..."""'''...'''。行尾会自动包含在字符串中,但是可以pass在行尾添加\来防止这种情况。下面的例子:

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

产生以下输出(请注意,不包括初始换行符):

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

字符串可以使用+运算符连接(粘合在一起),并使用*重复:

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

彼此相邻的两个或多个字符串 Literals(即用引号引起来的 Literals)会自动串联在一起。

>>> 'Py' 'thon'
'Python'

当您要断开长字符串时,此Function特别有用:

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

但是,这仅适用于两个 Literals,不适用于变量或表达式:

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

如果要连接变量或变量和 Literals,请使用+

>>> prefix + 'thon'
'Python'

字符串可以索引(带下标),第一个字符的索引为 0.一个字符只是一个大小为一的字符串:

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

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

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

注意,由于-0 与 0 相同,因此负索引从-1 开始。

除了索引之外,还支持切片。虽然索引用于获取单个字符,但是* slicing *允许您获取子字符串:

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

请注意如何始终包括开始,而总是排除结束。这可以确保s[:i] + s[i:]始终等于s

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

切片索引具有有用的默认值。Ellipsis的第一索引默认为零,Ellipsis的第二索引默认为要切片的字符串的大小。

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

记住切片工作方式的一种方法是将索引视为指向字符之间的,第一个字符的左边缘编号为 0.然后,* n 个字符串的最后一个字符的右侧边缘具有索引 n *,例如:

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

数字的第一行给出索引 0…6 在字符串中的位置;第二行给出相应的负索引。从* i j 的切片由分别标记为 i j *的边之间的所有字符组成。

对于非负索引,如果切片的长度均在索引范围内,则它们的长度就是索引的差。例如,word[1:3]的长度为 2.

try使用太大的索引将导致错误:

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

但是,超出范围的切片索引在用于切片时会得到妥善处理:

>>> word[4:42]
'on'
>>> word[42:]
''

Python 字符串不能更改,它们是immutable。因此,分配给字符串中的索引位置会导致错误:

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

如果您需要其他字符串,则应创建一个新字符串:

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

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

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

See also

3.1.3. Unicode 字符串

从 Python 2.0 开始,程序员可以使用一种新的数据类型来存储文本数据:Unicode 对象。它可以用于存储和处理 Unicode 数据(请参阅http://www.unicode.org/),并且可以与现有的字符串对象很好地集成在一起,并在必要时提供自动转换。

Unicode 的优点是为现代和古代文本中使用的每个脚本中的每个字符提供一个序数。以前,脚本字符只有 256 种可能的序号。文本通常绑定到将普通字符 Map 到脚本字符的代码页。这尤其在软件的国际化(通常写为i18n'i' 18 个字符'n')方面引起极大的混乱。 Unicode pass为所有脚本定义一个代码页来解决这些问题。

在 Python 中创建 Unicode 字符串与创建普通字符串一样简单:

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

引号前面的小'u'表示应该创建 Unicode 字符串。如果要在字符串中包括特殊字符,则可以使用 Python * Unicode-Escape *编码来实现。以下示例显示了如何:

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

转义序列\u0020表示在给定位置插入 Unicode 字符,其序号为 0x0020(空格字符)。

其他字符pass将它们各自的序数值直接解释为 Unicode 序数来解释。如果您在许多西方国家/locale 使用标准的 Latin-1 编码形式的 Literals 字符串,则可以很方便地发现 Unicode 的低 256 个字符与 Latin-1 的 256 个字符相同。

对于 maven,还有一种原始模式,就像普通字符串的原始模式一样。您必须在开头引号前面加上“ ur”,以使 Python 使用* Raw-Unicode-Escape *编码。仅当小“ u”前面的反斜杠数量不均匀时,才会应用上述\uXXXX转换。

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

当您必须 Importing 大量反斜杠时,原始模式最有用,正则表达式中可能需要。

除了这些标准编码外,Python 还提供了其他一系列基于已知编码创建 Unicode 字符串的方式。

内置Functionunicode()提供对所有注册的 Unicode 编解码器(编码器和 DECoders)的访问。这些编解码器可以转换的一些更知名的编码是* Latin-1 ASCII UTF-8 UTF-16 *。后两种是可变长度编码,将每个 Unicode 字符存储在一个或多个字节中。默认编码通常设置为 ASCII,可pass 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)

为了使用特定的编码将 Unicode 字符串转换为 8 位字符串,Unicode 对象提供了一个encode()方法,该方法采用一个参数,即编码的名称。首选使用小写编码名称。

>>> u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

如果您具有采用特定编码的数据,并且想要从中生成相应的 Unicode 字符串,则可以将unicode()函数与编码名称一起用作第二个参数。

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

3.1.4. Lists

Python 知道许多* compound 数据类型,用于将其他值组合在一起。最通用的是 list *,可以将其写成方括号之间用逗号分隔的值(项目)的列表。列表可能包含不同类型的项目,但通常所有项目都具有相同的类型。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

像字符串(以及所有其他内置的sequence类型)一样,可以对列表进行索引和切片:

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

所有切片操作都返回一个包含所请求元素的新列表。这意味着以下切片将返回列表的新(浅)副本:

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

列表还支持诸如串联的操作:

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

与字符串immutable不同,列表是mutable类型,即可以更改其内容:

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

您还可以使用append() 方法在列表的末尾添加新项(我们将在以后看到有关方法的更多信息):

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

也可以分配给切片,这甚至可以更改列表的大小或完全清除它:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

内置Functionlen()也适用于列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

可以嵌套列表(创建包含其他列表的列表),例如:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. 编程的第一步

当然,与将两个和两个加在一起相比,我们可以将 Python 用于更复杂的任务。例如,我们可以编写* 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

本示例介绍了几个新Function。

  • 第一行包含多个赋值:变量ab同时获得新值 0 和 1.在最后一行,再次使用它,表明右侧的表达式首先被求值,然后作业进行。右侧表达式从左到右计算。

  • 只要条件(此处为b < 10)保持为真,就会执行while循环。在 Python 中,就像在 C 中一样,任何非零整数值都为 true;零为假。条件也可以是字符串或列表值,实际上可以是任何序列;长度非零的任何内容为 true,空序列为 false。示例中使用的测试是一个简单的比较。标准比较运算符的编写方式与 C 相同:<(小于),>(大于),==(等于),<=(小于或等于),>=(大于或等于)和!=(不等于)。

  • 循环的* body indented *:缩进是 Python 对语句进行分组的方式。在交互式提示下,您必须为每个缩进的行键入一个制表符或空格。在实践中,您将使用文本编辑器为 Python 准备更复杂的 Importing。所有体面的文本编辑器都具有自动缩进Function。以交互方式 Importing 复合语句时,必须在其后跟随一个空行以指示完成(因为解析器无法猜测您何时键入了最后一行)。请注意,基本块中的每一行都必须缩进相同的数量。

  • print语句写出给定表达式的值。它在处理多个表达式和字符串的方式上不同于仅编写要编写的表达式(就像我们在计算器示例中所做的那样)。字符串打印时不带引号,并且在项目之间插入空格,因此您可以很好地设置格式,如下所示:

>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536

尾部逗号避免在输出后出现换行符:

>>> a, b = 0, 1
>>> while b < 1000:
...     print b,
...     a, b = b, a+b
...
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之类的特殊字符在单引号('...')和双引号("...")中具有相同的含义。两者之间的唯一区别是,在单引号内无需转义"(但必须转义\'),反之亦然。