Python 安装
Python 基础语法
常见的算术(数学)运算符有:
加(+)、减(-)、乘(*)、除(/)、整除(//)、取余(%)、求平方(**)
赋值运算符有:
标准赋值: =
复合赋值:+=、-=、*=、/=、//=、%=、**=
Python 循环语句
while some:
pass
for i in range(start, end, step):
pass
for i in arr:
passPython 数据容器
列表 list

列表最多容纳 2**63-1 个数据。
- del 操作:删除元素,后面的元素向前移动
元组 tuple
t = ('hello', )
元组不可修改

字符串 string
- 字符串不可修改某个下标的数据。
- 单引号、双引号、三重引号
- 常用函数:
lower(),upper(),islower(),isupper()isalpha(),isalnum(),isdecimal(),isspace()(非空&空白字符),istitle()(仅首字母大写)startswith(),endswith()join(),split(),strip(),rstrip(),lstrip()

序列

my_list = [1, 2, 3, 4, 5]
new_list = my_list[1:4] # 下标1开始,下标4(不含)结束,步长1
print(new_list) # 结果:[2, 3, 4]
my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:] # 从头开始,到最后结束,步长1
print(new_tuple) # 结果:(1, 2, 3, 4, 5)
my_list = [1, 2, 3, 4, 5]
new_list = my_list[::2] # 从头开始,到最后结束,步长2
print(new_list) # 结果:[1, 3, 5]
my_str = "12345"
new_str = my_str[:4:2] # 从头开始,到下标4(不含)结束,步长2
print(new_str) # 结果:"13"
my_str = "12345"
new_str = my_str[::-1] # 从头(最后)开始,到尾结束,步长-1(倒序)
print(new_str) # 结果:"54321"
my_list = [1, 2, 3, 4, 5]
new_list = my_list[3:1:-1] # 从下标3开始,到下标1(不含)结束,步长-1(倒序)
print(new_list) # 结果:[4, 3]
my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:1:-2] # 从头(最后)开始,到下标1(不含)结束,步长-2(倒序)
print(new_tuple) # 结果:(5, 3)集合 set

字典 dict

from collections import defaultdict
m = defaultdict(list) # 默认值为空列表
m['hi'].append(1)
m['wow'].append(2)
m2 = defaultdict(int) # 默认值为 0
m2['hi'] += 1
m2['wow'] += 4Python 调试
Python 异常
try:
可能发生错误的代码
except:
如果出现异常执行的代码
try:
print(name)
except NameError as e:
print('name变量名称未定义错误')
try:
print(1/0)
except (NameError, ZeroDivisionError):
import traceback
traceback.print_exc()
print('ZeroDivision错误...')
else:
print('hi')
finally:
print('bye')断言
assert tmp_status == 'open', 'tmp status need to be open'断言一般用于在调试程序的时候使用,线上应该用异常处理。并且断言相对于正常判断+异常更耗时些。
在运行 Python 时传入 -O 选项,可以禁用断言。
Python logging 模块
Python 模块和包
自定义包
- 从物理上看,包就是一个文件夹,在该文件夹下包含了一个 init.py 文件,该文件夹可用于包含多个模块文件 。
- 从逻辑上看,包的本质依然是模块。
创建包

导入包(一)
import my_package.my_module1
my_package.my_module1.info_print1()
from my_package import *导入包(二)
注意:必须在 __init__.py 文件中添加 __all__ = [],控制允许导入的模块列表。例如下述内容,设置后,就无法使用 import my_package.my_module1 了。
__all__ = ["my_module2"]安装第三方包
pip install pandas
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas
Python 文件操作
文件读取
open(name, mode, encoding)
f = open('python.txt', 'r', encoding=”UTF-8)
# encoding的顺序不是第三位,所以不能用位置参数,用关键字参数直接指定| 模式 | 描述 |
|---|---|
| r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
| w | 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,原有内容会被删除。 如果该文件不存在,创建新文件。 |
| a | 打开一个文件用于追加。如果该文件已存在,新的内容将会被写入到已有内容之后。 如果该文件不存在,创建新文件进行写入。 |
| 操作 | 功能 |
|---|---|
| 文件对象 = open(file, mode, encoding) | 打开文件获得文件对象 |
| 文件对象.read(num) | 读取指定长度字节,不指定 num 读取文件全部 |
| 文件对象.readline() | 读取一行 |
| 文件对象.readlines() | 读取全部行,得到列表 |
| for line in 文件对象 | for 循环文件行,一次循环得到一行数据 |
| 文件对象.close() | 关闭文件对象 |
| with open() as f | 通过 with open 语法打开文件,可以自动关闭 |
文件写入
f = open('python.txt', 'w')
f.write('hello world')
f.flush()- 直接调用 write,内容并未真正写入文件,而是会积攒在程序的内存中,称之为缓冲区
- 当调用 flush 的时候,内容会真正写入文件
- 这样做是避免频繁的操作硬盘,导致效率下降(攒一堆,一次性写磁盘)
- close()方法,带有 flush()方法的功能
- 文件如果不存在,使用”w”模式,会创建新文件
- 文件如果存在,使用”w”模式,会将原有内容清空
文件追加
f = open('python.txt', 'a')
f.write('hello world')
f.flush()- a 模式,文件不存在会创建文件
- a 模式,文件存在会在最后,追加写入文件
- 可以使用”\n”来写出换行符
其他补充
类型注解
函数的类型注解
def fun(x: int, y:int, data:list[int]) -> int:
return 3Union 类型
my_list: list[int] = [1,2,3]
my_dict: dict[str, int] = {'age': 11, 'num': 3}
from typing import Union
my_list: list[Union[str, int]] = [1,2 ,'hi','func']
my_dict: dict[str, Union[str,int]] = {'age': 11, 'num': 3, 'name':'wsc'}
def func(data: Union[int, str]) -> Union[int, str]:
pass单例模型
# 在单个文件中定义
class StrTools:
pass
str_tool = StrTools()
# 另一个文件使用
from test import str_tool
s1 = str_tool
s2 = str_tool
print(s1)
print(s2)