0%

Python

Python 学习记录

基本语法

注释

1
2
3
4
5
6
# 单行注释

"""
多行注释
多行注释
"""

行与缩进

不使用 {},而是使用缩进的方式来表示代码块

1
2
3
4
if True:
print ("True")
else:
print ("False")

多行语句

过长的语句采用 \ 换行

1
2
3
total = item_one + \
item_two + \
item_three

[], {}, 或 () 中的多行语句,不需要使用反斜杠 \

1
2
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']

引入模块

引入整个模块

1
import somemodule

引入模块中的部分函数

1
from somemodule import somefunction

变量

赋值

Python 中的变量赋值不需要类型声明,所以每个变量在使用前都必须赋值。

1
a = 1

多个变量赋值

1
a, b = 1, 'abc'

允许连等

1
a = b = 1

Number

支持 int、float、bool、complex

可以用 type() 来查询变量所指的对象类型

1
2
a, b, c, d = 1, 1.5, True, 4+3j
print(type(a), type(b), type(c), type(d))

输出:

1
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

数值运算

与其他语言不同,python 中 \\\ 都是除法,但是 \ 得一浮点数,\\ 得一整数

1
2
3
4
>>> 1 / 2
0.5
>>> 1 // 2
0

** 表示乘方,x ** y 即 $x^y$

1
2
>>> 2 ** 5
32

类型转换

转换成数字类型直接用 int()float() 这样的强制类型转换

1
2
3
4
5
6
7
>>> a, b, c = 1, 1.2, '123'
>>> float(a)
1.0
>>> int(b)
1
>>> int(c)
123

String

可以用 '" 来创建字符串

Python 不支持单字符类型,单字符也当作字符串处理

索引与截取

字符串索引,前面从 0 开始,后面从 -1 开始

字符串截取

1
str[上标 : 下标]

范围是 [上标, 下标),不包括下标

1
2
3
4
5
6
7
8
9
>>> str = 'python'
>>> str[0:3]
'pyt'
>>> str[2:-1]
'tho'
>>> str[1:]
'ython'
>>> str[:-1]
'pytho'

List

列表 List 的数据项不需要是相同的类型,索引方式与 String 相同

1
2
3
4
5
6
7
>>> list = [1, 2, "Red"]
>>> list[0]
1
>>> list[-1]
'Red'
>>> list[1:]
[2, 'Red']

使用 append() 方法来添加列表项

1
2
3
>>> list.append("Green")
>>> list
[1, 2, 'Red', 'Green']

也可用 +* 来扩展 List

1
2
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
1
2
>>> [1] * 3
[1, 1, 1]

使用 del 语句来删除列表的的元素

1
2
3
>>> del list[2]
>>> list
[1, 2, 'Green']

求长度

1
2
>>> len([1, 2, 3])
3

判断元素是否在 List 中

1
2
>>> 1 in [1, 2, 3]
True

遍历 List

1
2
for x in [1, 2, 3]:
...

判断两个 List 是否相同,需引入 operator 模块

1
2
3
4
5
import operator

list1, list2, list3 = [1, 2], [1, 2], [2, 3]
print(operator.eq(list1, list2)) # True
print(operator.eq(list1, list3)) # False

Tuple

元祖 Tuple 与 List 类似,但是 Tuple 不能修改

Dictionary

数据类型转换

运算符

部分运算符

运算符 描述 实例
**

语句

if

while

for

break

continue

pass

命令行参数

函数

模块

文件

异常

测试