跳至主要內容

3. 速览

Zhao Bin笔记backendpython

3. 速览

3.1 Python 用作计算器

3.1.1 数字

除了 int 和 float,Python 还支持其他数字类型,例如 Decimal 或 Fraction。

3.1.2 字符串

用单引号('……')或双引号("……")标注的结果相同,可交替使用,例 "doesn't"'"Yes," they said.'
反斜杠 \ 用于转义,例 'doesn\'t'

字符串字面值可以包含多行。 一种实现方式是使用三重引号:"""..."""'''...'''。 字符串中将自动包括行结束符,但也可以在换行的地方添加一个 \ 来避免此情况(避免换行,就是加 \ 后不换行)。 参见以下示例:

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

输出如下(请注意开始的换行符没有被包括在内):

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

字符串可以用 + 拼接,也可以用 * 重复,相邻的两个或多个 字符串字面值 (引号标注的字符)会自动合并。
拼接分隔开的长字符串时,这个功能特别实用。

print(3 * 'un' + 'ium') # 'unununium'
print('Py' 'thon') # 'Python'
print('Put several strings within parentheses '
      'to have them joined together.')

字符串支持 索引 (下标访问),第一个字符的索引是 0。单字符没有专用的类型,就是长度为一的字符串。
索引还支持负数,用负数索引时,从右边开始计数,注意,-0 和 0 一样,因此,负数索引从 -1 开始。

word = "python"
print(word[0])    # p
print(word[-1])   # n

除了索引,字符串还支持 切片。索引可以提取单个字符,切片 则提取子字符串,前闭后开
切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾。
负数代表从右边开始数。
输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:] 总是等于 s
索引越界会报错,但是,切片会自动处理越界索引。

print(word[0:2])    # py
print(word[2:5])    # tho
print(word[:2])     # py
print(word[4:])     # on
print(word[-2:])    # on
print(word[42])     # IndexError: string index out of range
print(word[4:42])   # on
print(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

其他补充:

试一试:

python 3.1/str-demo.py

3.1.3 列表

列表 ,是用方括号标注,逗号分隔的一组值。列表 可以包含不同类型的元素,但一般情况下,各个元素的类型相同。
和字符串(及其他内置 sequence 类型)一样,列表也支持索引和切片。
切片操作返回包含请求元素的新列表。
列表还支持合并操作。

squares = [1, 4, 9, 16, 25]
print(squares[0])       # 1
print(squares[-1])      # 25
print(squares[-3:])     # [9, 16, 25] 返回新的列表
print(squares[:])       # [1, 4, 9, 16, 25] 返回列表的浅拷贝
print(squares + [36, 49, 64])   # [1, 4, 9, 16, 25, 36, 49, 64]

与 immutable 字符串不同, 列表是 mutable 类型,其内容可以改变。
append() 方法 可以在列表结尾添加新元素。
为切片赋值可以改变列表大小,甚至清空整个列表。
内置函数 len() 也支持列表。
还可以嵌套列表(创建包含其他列表的列表)。

cubes = [1, 8, 27, 65, 125]  # something's wrong here
cubes[3] = 64
cubes.append(6 ** 3)
print(cubes)          # [1, 8, 27, 64, 125, 216]

letters = ['a', 'b', 'c', 'd', 'e', 'f']
letters[2:5] = ['C', 'D', 'E']
print(letters)        # ['a', 'b', 'C', 'D', 'E', 'f']
letters[2:5] = []     # 删除 2:5
print(letters)        # ['a', 'b', 'f']

试一试:

python 3.1/list-demo.py

3.2 走向编程的第一步

打印斐波那契数列:

"""
Fibonacci series
"""

a, b = 0, 1
while a < 10:
  # print(a)
  print(a, sep = ', ', end = '\n')   # print 默认带换回,使用 end 改用自己指定的字符
  a, b = b, a + b

试一试:

python 3.2/fibonacci.py

本例引入的新功能:

  • 第一行中的 多重赋值:变量 ab 同时获得新值 01,最后一行又用了一次多重赋值。
  • while 循环,循环体缩进。