数字、字符串和列表

……

‘>>>’表示进入python命令,使用’#’进行注释,’…’表示继续输入代码,与上文是一个整体。

数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# + - * / // % **
>>> 2 + 2
4
>>> 4 * 3.75 - 1 # 有整数有小数,结果仍是小数
14.0
>>> 17 / 3 # 一般除法,总是返回小数
5.666666666666667
>>> 17 // 3 # 整除
5
>>> 17 % 3 # 求余数
2
>>> 2 ** 7 # 计算多少次方
128

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax # 直接显示计算结果时,结果保存在变量‘_’中
12.5625
>>> price + _ # 不要对变量‘_’进行赋值
113.0625
>>> round(_, 2)
113.06

字符串

可以用单引号或者双引号表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> 3 * 'un' + 'ium'  # 字符串连接用'+',重复用'*'
'unununium'
>>> text = ('Put several strings within parentheses ' # 常量字符串靠在一起时会自动连接
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

>>> word = 'Python'
>>> word[0] # 字符串可使用索引,没有特定的字符变量,仍是字符串
'P'
>>> word[-1] # 最后一个字母
'n'
>>> word[-6]
'P'
>>> word[0:2] # 切片操作,0,1
'Py'
>>> word[:2] + word[2:] # 0,1 2-最后
'Python'
>>> word[-2:]
'on
>>> word[4:42] # 切片操作超出索引范围
'on'
>>> word[42:]
''
>>> word[2:] = 'py' # 字符串不可变,不能进行赋值操作
...
TypeError: 'str' object does not support item assignment

>>> s = 'supercalifragilisticexpialidocious' # len()得到长度
>>> len(s)
34

使用”””…””” or ‘’’…’’’输出多行字符串。

1
2
3
4
5
6
7
8
9
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

列表

可以包含不同的类型,正常使用的还是同一类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
>>> squares = [1, 4, 9, 16, 25]  # 创建列表,用逗号隔开,[ , , ]
>>> squares
[1, 4, 9, 16, 25]
>>> squares[0] # 索引
1
>>> squares[-3:] # 切片
[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]
>>> cubes[3] = 64 # 可变,可以重新赋值
>>> cubes
[1, 8, 27, 64, 125]
>>> cubes.append(216) # 使用append()在末尾添加新内容
>>> cubes.append(7 ** 3)
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = [] # 清除某些内容
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = []
>>> letters
[]
>>> letters = ['a', 'b', 'c', 'd'] # len()得到长度
>>> 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'

注意

1
2
3
4
5
6
>>> a, b = 0, 1
>>> while b < 1000:
... print(b, end=',') # 'end'用于指定输出结束符号,默认为换行符
... a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,