Python知识大全。
https://github.com/daacheng/PythonBasic 平时工作中常用的Python零碎知识总结,爬虫学习总结与练习,Python数据分析学习总结
https://github.com/looly/python-basic 老齐(qiwsir)的Python基础教程
https://github.com/MiracleYoung/You-are-Pythonista
https://github.com/Prodesire/Python-Guide-CN Python最佳实践指南
基础语法、控制流、函数、模块、文件操作、异常处理、面向对象编程
1. 程序交互
input():带提示语的input。name=input(‘Please enter your name:’) 把输入以字符串的形式保存在name里
print():print多项、print的%格式化占位符、print的format形式 #可以接收多参
三引号:原样输出
转意符号
学习,思考,应用,校正。人做事情,都需要有个反馈,反馈的周期越久,感觉上就越困难。很多大事情,都是由一个个小事务重复或迭代而成,每个小事务中,包含了反馈和校正。学了什么,启示是什么,和其它知识的联系是什么
r:优先级最高
:把字母转义为特殊字符。防止引号表示字符串。
\n:制表符
\t:换行符
1 | print('a\nb') |
2. 文件读写
2.1. 无with
1 | f= open("file1.txt",encoding='utf-8')#不写encoding,默认为操作系统编码 |
2.2. 有with
1 | with open("file.txt",encoding='utf-8')as f: |
2.3. readline()
默认从文件左上角开始,读取一行,指针下移。通过f.seek()可改变指针位置和要开始读的内容。
1 | with open("file.txt",encoding='utf-8')as f: |
2.4. readlines()
从文件左上角开始,将文件内容读取到列表中。
1 | with open("file.txt",encoding='utf-8')as f: |
2.5. 不打印换行符
print(,end=’’)
1 | with open('file.txt','r',encoding='utf-8',newline='') as f: |
2.6. r+
按读的内容和指针位置逐行覆盖原来的内容
1 | with open('file.txt','r+',encoding='utf-8') as f: #从指针位置所在处写入 |
2.7. a+
写到文件最后
1 | with open('file.txt','a+',encoding='utf-8') as f: |
2.8. w+
在with那行语句结束时,整个文件原来的内容被清空,无法读取原文件的数据。但后面的内容可以边读边写。
1 | with open('file.txt','wb+') as f: |
2.9. 查看文件编码
待查证
1 | with open('file.txt','a+',encoding='utf-8') as f: |
2.10. b模式不能指定编码
1 | with open('file.txt','rb') as f: |
2.11. flush(),tell(),seek(),truncate()
1 | flush() #文件内容从内存刷到硬盘 |
2.12. 打印文件最后一行
1 | with open("file.txt",'rb') as f: |
3. 字符串
https://docs.python.org/3/library/string.html
3.1. dir(str)
1 | dir(str) |
upper()/lower():改变字符串中字母的大小写。
strip():删除字符串首尾空白符(如’\n’、’\n\r’)或指定字符。
lstrip():删除字符串左边空白符或指定字符。
rstrip():删除字符串右边空白符或指定字符。
去空格及特殊符号:
1 | s.strip().lstrip().rstrip(',') |
3.2. *
1 | str1 = 'Ab' |
3.3. +
1 | str1='a' |
3.4. join
1 | # S.join(seq) #把seq代表的字符串序列,用S连接起来 |
3.5. format及百分号操作符
默认:顺序传递
标准格式:{位置:值}
https://docs.python.org/3/library/string.html#format-string-syntax
1 | '{1} is better than {0}'.format('a','b') |
百分号操作符
%操作符:格式化符号。更高级别的控制。
- %和字母间加数字,点前为总长,点后为小数位数。
eg:%S%d%4.2f:占位符(格式化符号) - %s:字符串
- %d:整数
- %f:浮点数
- %5d:前面添加空格,总长度为5
- %4.2f:总长4,2个小数位的浮点数
print(“I’m %s. I’m %d year old” % (‘Vamei’, 99))
3.6. split()
分割字符串
split():按指定分隔符来切割字符串,返回列表。无分隔符时,默认分隔符是空格。
1 | # S.rsplit([sep, [maxsplit]]) |
3.7. splitlines()
按行分割字符串
1 | S.splitlines([keepends]) |
3.8. replace()
replace():替换目标字符串中的子串。
1 | S.replace(oldstr, newstr, [count]) |
3.9. translate()
批量替换
1 | # S.translate(table[,deletechars]) |
3.10. index()
查找字符,返回第一个字符出现的位置。< 0 为未找到
1 | str = 'strchr' |
3.11. find()
查找字符串
1 | sStr1 = 'abcdefg' |
3.12. index、rfind、rindex、count
1 | # 返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索 |
3.13. ljust、rjust、center、zfill
字符串在输出时的对齐
1 | str = "this is string example wow!!!" |
3.14. cmp(str1,str2)
比较字符串。http://www.runoob.com/python/func-number-cmp.html
3.15. len(str)
1 | sStr1 = 'strlen' |
3.16. [:]
字符串切片
1 | tr1 = '1234567890' |
3.17. lower()、upper()、swapcase()、capitalize()
1 | S='abEfeDg' |
3.18. encode、decode
字符串还有一对编码和解码的函数
1 | # S.encode([encoding,[errors]]) |
3.19. startswith、endswith、is
字符串的测试、判断函数
这一类函数在string模块中没有,这些函数返回的都是bool值
1 | S.startswith(prefix[,start[,end]]) |
3.20. atoi、atol、atof
字符串类型转换函数,这几个函数只在string模块中有
1 | string.atoi(s[,base]) |
3.21. and
如果为真,则返回左边第一个真值。
1 | sStr1 = '12345678' |
3.22. for in, if in
扫描字符串
1 | # strpbrk(sStr1,sStr2) |
3.23. addslashes 的实现
1 | def addslashes(s): |
3.24. 取字母与数字
1 | def OnlyCharNum(s): |
3.25. 说明
3.25.1. 字符串对象是不可改变的
也就是说在python创建一个字符串后,你不能把这个字符中的某一部分改变。
任何上面的函数改变了字符串后,都会返回一个新的字符串,原字串并没有变。
3.25.2. 也有变通的办法的
可以用S=list(S)这个函数把S变为由单个字符为成员的list.
这样的话就可以使用S[3]=’a’的方式改变值,然后再使用S=” “.join(S)还原成字符串
4. 特殊方法
面向对象编程的类中具有特殊意义的方法
方法名|含义
–|–
init()|初始化,进行初始化操作
del()|在对象消失前一刻用的
len()|对对象执行len()函数调用时,自动触发。一般用于设置对象长度。’’’def len(self): return’’’ 一个类的预设的长度
str()|对对象使用print()或str()时被自动调用,返回字符串
5. 数据库
5.1. pymysql
pip install pymysql --user- /xampp/phpMyadmin,打开config.inc.php文件,查看MySQL配置的用户和密码
参考教程:
- 菜鸟教程:mysql 、mysql-connector
5.2. 错误处理
DB API中定义了一些数据库操作的错误及异常,下表列出了这些错误和异常:
| 异常 | 描述 |
|---|---|
| Warning | 当有严重警告时触发,例如插入数据是被截断等等。必须是 StandardError 的子类。 |
| Error | 警告以外所有其他错误类。必须是 StandardError 的子类。 |
| InterfaceError | 当有数据库接口模块本身的错误(而不是数据库的错误)发生时触发。 必须是Error的子类。 |
| DatabaseError | 和数据库有关的错误发生时触发。 必须是Error的子类。 |
| DataError | 当有数据处理时的错误发生时触发,例如:除零错误,数据超范围等等。 必须是DatabaseError的子类。 |
| OperationalError | 指非用户控制的,而是操作数据库时发生的错误。例如:连接意外断开、 数据库名未找到、事务处理失败、内存分配错误等等操作数据库是发生的错误。 必须是DatabaseError的子类。 |
| IntegrityError | 完整性相关的错误,例如外键检查失败等。必须是DatabaseError子类。 |
| InternalError | 数据库的内部错误,例如游标(cursor)失效了、事务同步失败等等。 必须是DatabaseError子类。 |
| ProgrammingError | 程序错误,例如数据表(table)没找到或已存在、SQL语句语法错误、 参数数量错误等等。必须是DatabaseError的子类。 |
| NotSupportedError | 不支持错误,指使用了数据库不支持的函数或API等。例如在连接对象上 使用.rollback()函数,然而数据库并不支持事务或者事务已关闭。 必须是DatabaseError的子类。 |
5.3. OperationalError: (1045, “Access denied for user ‘testuser’@’localhost’ (using password: YES)”)
数据库连接错误,如何添加密码
6. 样式
1 | # Python代码块: |
7. 列表
Python列表
定义:相关数据的集合。数据的一种保存形式(相对于变量)。
索引:list[0]、list[-1]
申明:[],英文逗号隔开。
空列表(初始化):list1=[]
增:list1.append('a')
删:del list1[i]
改: 直接list[i]=newdata
切片: list[m:n:i] 左闭右开,i为步距。m省略的话,默认为0。n:-1。i:1
1 | myList=[1,2,3,4,5,'hello'] |
8. 字典
列表和元组是数据集合。字典是键值对集合。
字典键重合的问题。字典的改和增。
列表和元组的索引对应字典的键。
键为数字的字典。
字典除了用{}申明外,还可以用dict()申明,用dict()时,键不能带引号。否则报错 SyntaxError: keyword can't be an expression
学习,思考,应用,校正。人做事情,都需要有个反馈,反馈的周期越久,感觉上就越困难。很多大事情,都是由一个个小事务重复或迭代而成,每个小事务中,包含了反馈和校正
列表和元组形式上是[]、()的区别。元组的值不能修改。
定义:数据对集合。
申明:字典的关键字必须是唯一的。不能重复。但申明时不会报错。后面的键值对会自动覆盖前面的同名键值对。
{}没写而且没调用dict函数会报错SyntaxError: invalid syntax
1 | # 重复的键 |
8.1. 查
dicName[‘keyName’]
8.2. 改
dicName[‘keyName’]=newData
8.3. 增
dicName[‘keyName’]=newData
8.4. 删
del dicName[‘keyName’]
8.5. 排序
用字典的值对字典进行排序,将{1: 2, 3: 4, 4:3, 2:1, 0:0}按照字典的值从大到小进行排序。
1 | import operator |
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
对字典进行排序是【不可能】的,只有把字典【转换】成另一种方式才能排序。字典本身是无序的,但是如列表元组等其他类型是有序的,所以需要用一个元组列表来表示排序的字典。
9. 类型转换
int(number)
float(number)
for key,value in dict.items()
Python 100例 https://www.w3cschool.cn/python/python-100-examples.html
10. 类
1 | class Person: # 创建类 |
11. 函数、类,可变与不可变
1 | a = 1 |
12. 安装
Python3 in Ubuntu:
apt list –installed | grep python
sudo apt-get update
sudo apt-get upgrade python3
sudo apt install python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python-dev
pip3 -V
sudo apt install -y python3-venv
mkdir wx
cd wx
python3 -m venv wx
ls wx
source wx/bin/activate
vim hello.py
i(Escape)
zz
:wq
pip3 install flask
python3 hello.py
https://stackoverflow.com/questions/38298652/permissionerror-errno-13-permission-denied-flask-run change port to 5000(tencent denies port 80)
https://vitux.com/install-python3-on-ubuntu-and-set-up-a-virtual-programming-environment/
13. Python第三方库
基本格式:(安装时,把name替换为要安装的第三方库)
pip install namepip install -i https://pypi.tuna.tsinghua.edu.cn/simple name
- 科学计算的包,如Numpy、Scipy、Pandas和Matplotlib。
- 机器学习、生物医学和天体物理学计算,如Scikit-Learn、BioPython。
- 获取网页:requests、urllib、selenium
- 解析数据:lxml、bs4的BeautifulSoup、re(标准库)
- 存储数据:MySQL、MongoDB
14. 基础算法
14.1. 循环打印输出从1到100的所有奇数
1
2
3for i in range(1,101):
if i % 2 == 1:
print (i)14.2. 字符串批量替换
请将字符串“你好$$$我正在学Python@#@#现在需要&&&修改字符串”中的符号变成一个空格,需要输出的格式为:“你好 我正在学Python现在需要 修改字符串”。1
2
3
4
5
6
7
8
9# 方法1
str1 = '你好$$$我正在学Python@#@#现在需要&%&%&修改字符串'
str2 = str1.replace('$$$', ' ').replace('@#@#', ' ').replace('&%&%&', ' ')
print (str2)
# 方法2
import re
str1 = '你好$$$我正在学Python@#@#现在需要&%&%&修改字符串'
str2 = re.sub('[$@#&%]+', ' ' ,str1)
print (str2)14.3. 输出9×9乘法口诀表
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64# 此法会有多余的换行和末尾对于的空格
for i in range(1,10):
for j in range(1,i+1):
print('{}×{}={}'.format(j,i,j*i),end=' ')
print('\n')
# 更好的方法,没有对齐
for i in range(1,10):
for j in range(1,i+1):
print('{}×{}={} '.format(j,i,j*i),end='')
print('')
# 最好的方法 这里是对齐的。由此可见,'\t'是用来【显示】对齐的,但似乎len就是1
for i in range(1,10):
for j in range(1,i+1):
print('{}×{}={}\t'.format(j,i,j*i),end='')
print('')
# 最好的方法 这里是对齐的
for i in range(1, 10):
for j in range(1, i+1):
print ("%dx%d=%d\t" % (j, i, i*j), end="")
print("")
# 1×1=1
# 1×2=2 2×2=4
# 1×3=3 2×3=6 3×3=9
# 1×4=4 2×4=8 3×4=12 4×4=16
# 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
# 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
# 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
# 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
# 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
# 1×1=1
# 1×2=2 2×2=4
# 1×3=3 2×3=6 3×3=9
# 1×4=4 2×4=8 3×4=12 4×4=16
# 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
# 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
# 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
# 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
# 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
# 1×1=1
# 1×2=2 2×2=4
# 1×3=3 2×3=6 3×3=9
# 1×4=4 2×4=8 3×4=12 4×4=16
# 1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
# 1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
# 1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
# 1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
# 1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81
# 1x1=1
# 1x2=2 2x2=4
# 1x3=3 2x3=6 3x3=9
# 1x4=4 2x4=8 3x4=12 4x4=16
# 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
# 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
# 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
# 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
# 1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
print(len('{}\t'.format(5*6)))
print(len('{}\t'.format(5*60)))
print(len('{}\t'.format(5*600)))
print(len('{}\t'.format(5*6000)))
# 3
# 4
# 5
# 614.4. 利润分段计算
请写出一个函数,当输入函数变量月利润为I时,能返回应发放奖金的总数。例如,输出“利润为100000元时,应发放奖金总数为10000元”。
其中,企业发放的奖金根据利润提成。
利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;
利润在20万元到40万元之间时,高于20万元的部分可提成5%;
利润在40万元到60万元之间时,高于40万元的部分可提成3%;
利润在60万元到100万元之间时,高于60万元的部分可提成1.5%;
利润高于100万元时,超过100万元的部分按1%提成。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
36def calcute_profit(I):
I = I / 10000
if I <= 10:
a = I * 0.01
return a * 10000
elif I <= 20 and I > 10:
b =0.25 + I * 0.075
return b * 10000
elif I <= 40 and I > 20:
c = 0.75 + I * 0.05
return c * 10000
elif I <= 60 and I > 40:
d = 0.95 + I * 0.03
return d * 10000
elif I <= 60 and I > 100:
e = 2 + I * 0.015
return e * 10000
else:
f = 2.95 + I * 0.01
return f * 10000
I = int(input('净利润:'))
profit = calcute_profit(I)
print ('利润为%d元时,应发奖金总数为%d元' % (I, profit))
def calcute_profit(I):
arr = [1000000,600000,400000,200000,100000,0] #这应该就是各个分界值了,把它们放在列表里方便访问
rat = [0.01,0.015,0.03,0.05,0.075,0.1] #这是各个分界值所对应的奖金比例值
r = 0 #这是总奖金的初始值
for idx in range(0,6): #有6个分界值当然要循环6次
if I > arr[idx]:
r = r + (I - arr[idx]) * rat[idx]
I = arr[idx]
return r
I = int(input('净利润:'))
profit = calcute_profit(I)
print ('利润为%d元时,应发奖金总数为%d元' % (I, profit))