3. Python简介

来源:互联网 发布:2016年进出口数据分析 编辑:程序博客网 时间:2024/05/17 08:37

3. Python简介

以下的示例中,输入和输出通过是否存在提示符(>>> and ...)来区分:如果要重复该示例,你必须在提示符出现后,输入提示符后面的所有内容;没有以提示符开头的行是解释器的输出。注意示例中出现从提示符意味着你一定要在最后加上一个空行;这用于结束一个多行命令。

本手册中的很多示例,甚至在交互方式下输入的示例,都带有注释。Python 中的注释以井号 # 为开始,直到物理行的末尾结束。注释可以从行首开始,也可以跟在空白或代码之后,但不能包含在字符串内。因为注释只是为了解释代码并且不会被Python解释器解释,所以敲入示例的时候可以忽略它们。

例如:

# this is the first commentspam = 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作为计算器 

让我们尝试一些简单的 Python 命令。启动解释器然后等待主提示符 >>> 。(这不需要很久。)

3.1.1. 数字

解释器可作为一个简单的计算器:你可以向它输入一个表达式,它将返回其结果。表达式语法非常简单: 运算符 +-* 及 / 的使用方法与其他语言一致 ( 例如 Pascal 或 C); 括号 (()) 可以用来进行分组。例如:

>>>
>>> 2 + 24>>> 50 - 5*620>>> (50 - 5*6) / 45.0>>> 8 / 5  # division always returns a floating point number1.6

整数型 (如2420)属于 int类型,带有小数部分的数字 (如5.01.6) 属于float浮点型 。在本教程的后面我们会看到更多关于数字类型的内容。

除法(/)总是返回一个float类型数。要做 floor 除法 并且得到一个整数结果(返回商的整数部分) 可以使用 // 运算符;要计算余数可以使用 %

>>>
>>> 17 / 3  # classic division returns a float5.666666666666667>>>>>> 17 // 3  # floor division discards the fractional part5>>> 17 % 3  # the % operator returns the remainder of the division2>>> 5 * 3 + 2  # result * divisor + remainder17

通过**计算n方[1]:

>>>
>>> 5 ** 2  # 5 squared25>>> 2 ** 7  # 2 to the power of 7128

等号 (=) 用于给变量赋值。赋值之后,在下一个提示符之前不会有任何结果显示:

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

如果变量未"定义"(即未赋值),使用的时候将会报错︰

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

完全支持浮点数;并且与混合的型操作数的运算符将整数操作数转换为浮点数︰

>>>
>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.5

在交互模式下,最后一个打印的表达式分配给变量 _这意味着把 Python 当做桌面计算器使用的时候,可以方便的进行连续计算,例如:

>>>
>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06

用户应该将这个变量视为只读的。不要试图去给它赋值 — — 你将会创建出一个独立的同名局部变量,并且屏蔽了内置变量的魔术效果。

除了 整型 和 浮点,Python 支持其他类型的数字,如 小数 和 分数Python 也具有内置支持的 复数,并使用 j 或 J 后缀 (例如指示的虚部3+5j).

3.1.2. 字符串

除了数值,Python 还可以操作字符串,可以用几种方法来表示。他们可以将括在单引号 ('...') 或双引号 ("...") 中,二者等价 [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," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'

在交互式解释器中,输出的字符串会用引号引起来,特殊字符会用反斜杠转义。虽然可能和输入看上去不太一样(括起来的引号可能会变),但是两个字符串是相等的。如果字符串中只有单引号而没有双引号,就用双引号引用,否则用单引号引用。print () 函数生成可读性更好的输出,通过省略引号和通过打印字符转义和特殊字符︰

>>>
>>> '"Isn\'t," she said.''"Isn\'t," she said.'>>> print('"Isn\'t," she said.')"Isn't," she 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 lineFirst line.Second line.

如果你不想以 \ 将被解释为特殊字符开头的字符,您可以通过添加 r 使用 原始字符串

>>>
>>> print('C:\some\name')  # here \n means newline!C:\someame>>> print(r'C:\some\name')  # note the r before the quoteC:\some\name

字符串可以跨多行。一种方法使用三重引号: """...""" 或 '''...'''行结尾会自动包含在字符串中,但它是可以通过在一行的末尾增加 \防止以下情况。下面的示例:

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'

相邻的两个或多个字符串字面量(用引号引起来的)会自动连接。

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

然而这种方式只能用于两个字符串的连接,变量或者表达式是不行的。

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

如果你想连接多个变量或者连接一个变量和一个字面量,使用“+”

>>>
>>> prefix + 'thon''Python'

这个功能在你想切分很长的字符串的时候特别有用:

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

字符串可以索引,第一个字符的索引值为0。Python没有单独的字符类型;一个字符就是一个简单的长度为1的字符串。

>>>
>>> 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 开始。

除了索引,还支持切片索引用于获得单个字符,切片让你获得子字符串:

>>>
>>> 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'

切片索引具有非常有用的默认值;省略的第一个索引默认为零,省略第二个索引默认为切片字符串的长度。

>>>
>>> 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。

试图使用太大的索引会导致错误:

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

但是,当用于切片时,超出范围的切片索引会优雅地处理:

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

Python 字符串不能更改 — — 他们是 不可变的因此,赋值给字符串索引的位置会导致错误:

>>>
>>> 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

请参阅

序列类型— str
字符串是序列类型的例子,它们支持这种类型的常见操作。
字符串方法
字符串支持大量的方法用于基本变换和搜索。
字符串格式化
字符串格式通过 str.format() 设置信息。
printf -style 字符串的格式化
在此更详细介绍了旧的格式设置操作调用字符串和 Unicode 字符串时 % 运算符的左的操作数。

3.1.3. 列表

Python 有几个 复合 数据类型,用来组合其他的值。最有用的是 列表,可以写成中括号中的一列用逗号分隔的值。列表可以包含不同类型的元素,但是通常一个列表中的所有元素都拥有相同的类型。

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

与字符串 (和所有其他内置 序列 类型)相似,列表可以被索引和切片︰

>>>
>>> squares[0]  # indexing returns the item1>>> 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]

与字符串的不可变特性不同,列表是可变的类型,例如可以改变它们的内容:

>>>
>>> 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[]

内建函数 len() 同样适用于列表:

>>>
>>> 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 用于比 2 加 2 更复杂的任务。例如,我们可以写一个生成斐波那契 初始子序列的程序,如下所示:

>>>
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:...     print(b)...     a, b = b, a+b...112358

本示例介绍了几种新功能。

  • 第一行包含 多个赋值 ︰ 变量 和 同时获得新值 0 和 1。最后一行又这样使用了一次,说明等号右边的表达式在赋值之前首先被完全解析。右侧表达式是从左到右计算的。

  • 当循环条件 (here: b < 10) 保持为 true 时 while 循环执行。在 Python 中,像在 C 中,任何非零整数值为 True;零是 False。条件也可能是一个字符串或列表值,事实上任何序列;任何非零长度是真的,空序列都是false。示例中使用的测试是一个简单的比较。标准的比较运算符和C语言一样: < (小于), > (大于), == (等于), <= (小于等于), >=(大于等于) and != (不等于).

  • 循环 是缩进 的:缩进是 Python 分组语句的方式。交互式输入时,你必须为每个缩进的行输入一个 tab 或(多个)空格。实践中你会用文本编辑器来编写复杂的 Python 程序;所有相对合适的文本编辑器都有自动缩进的功能。交互式输入复合语句时,最后必须跟随一个空行来表示结束(因为解析器无法猜测你什么时候已经输入最后一行)。注意基本块内的每一行必须按相同的量缩进。

  • print() 函数写入给定的参数。与仅仅输出你想输出的表达式不同(就像我们在前面计算器的例子中所做的),它可以输出多个参数、浮点数和字符串。打印出来的字符串不包含引号,项目之间会插入一个空格,所以你可以设置漂亮的格式,像这样:

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

    关键字参数 end 可以避免在输出后面的空行,或者可以指定输出后面带有一个不同的字符串:

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

脚注

[1]因为 ** 的优先级高于 -, -3**2会被解释为 -(3**2) 并得到结果 -9.。为了避免这一点并得到结果 9, 你可以使用 (-3)**2[2]不像其他语言,类似 \n 的特殊字符与单引号 ('...') 双引号 ("...") 有相同的含义。两者唯一的不同在于使用单引号你不需要转义 " (但是你必须转义 \') ,反之亦然。
0 0