Python基础语法 如果有相应的coding基础,那这篇文章对你而言的意义仅限于python的一些常见语法等,并不能有效帮助你更好地学习Python;但是如果你是和我一样刚接触Python的话,那这篇文章值得你看一遍。
一些协助操作
操作
dir()
返回包含的方法以及操作以及人特殊属性
help()
帮助函数,返回类的参考手册
id()
获取当前变量地址
先从一个小游戏开始 一个简单的猜数游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import random secret = random.randint(1 ,100 ) temp = input ('输入一个数\n' ) guess = int (temp)while guess != secret: temp = input ('猜错了,重新猜\n' ) guess = int (temp) if guess == secret: print ("猜中了" ) else : if guess < secret: print ('猜小了' ) else : print ('猜大了' )print ('游戏结束' )
1、数据类型 Python中的数据类型有以下三种
str(字符串)、float(浮点型)、int(整型)
三种类型之间可以通过int(),float(),str()
相互转换,但是有一定限制,比如某些时候就无法从str
转float
如上所示,str类型转float失败,但是某些情况下又是正常的,如果letter是数字的话,是可以进行类型转换的。如下所示:
具体用法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 firstStr = '你好' secondStr = '我是小明同学' thirdStr = firstStr + secondStrprint (thirdStr) print (1500000000 )print (1.5e9 ) print (True + True ) a = str ('你好' ) b = int (1314 ) c = float (520 )print ('判断a、b、c三者是否属于str字符变量' )print (isinstance (a,str )) print (isinstance (b,str )) print (isinstance (c,str ))
2、操作符 python中的操作符与C++有一丝区别
算术操作符:除了+-*/
,多了一个**(乘方) //(浮点除法(四舍五入))
比较操作符:python的标准比较操作符有:< <= > >= == != <>,根据表达式的真假,返回True/False布尔值数据类型
逻辑操作符:and、or、not是python提供的逻辑操作符,其作用是把表达式连接在一起,得到一个布尔值,
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 a = 8 // 3 print (a) b = 8 / 3 print (b) c = 2 ** 4 print (c) wrong = not True print (wrong) a,b = 4 ,5 max = a if a > b else bprint ('max number是a' ) if a > b else print ('max number是b,值为' ,b) a = int (input ("Input a: " )) b = int (input ("Input b: " ))print ("a大于b" ) if a > b else (print ("a小于b" ) if a < b else print ("a等于b" ))True and True True and False True or False not False and True
一道小的逻辑运算编写 如下所示为简单的成绩判断代码。后边标注了悬挂else,python是根据缩进判断if-else的匹配,所以可以有效的避免else的悬挂问题。
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 score = input ('请输入你的成绩:\n' ) temp = int (score)if temp >= 90 : print ("A" )elif 80 <= temp < 90 : print ('B' )elif 70 <= temp < 80 : print ('C' )elif temp < 70 : print ('D' )else : print ('输入错误\n' ) temp = input ('请输入成绩\n' ); temp = int (temp)if (temp > 80 ): print ('成绩在80以上\n' ) if (temp > 90 ): print ('成绩优异' ) else : print ('成绩良好,确认完毕' )else : print ("因为temp(" ,temp,")小于80,所以这里就是所谓的悬挂else," "相匹配的是上边temp>90所对应的if,但是python可以避免," "所以这里的else对应的是temp>80所对应的if" )
什么是悬挂else?悬挂else是面试中最常见的一个问题,就是C\C++中的else
与离他最近的if
匹配如下所示:
1 2 3 4 5 6 7 int i = 0 ; cin >> i;if (i > 50 ) if (i>55 ) cout << "稍微有点重" ; else cout << "这个我喜欢" ;
3、列表 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 member = ['A' ,'B' ,'C' ,'D' ,'E' ]print ('打印member列表:\n' ,member) mix = [1 ,'二' ,3.14 ,[1 ,2 ,3 ]]print ('打印mix列表:' )print ('位置' , '|' , '元素' ) i = 0 for each in mix: i = i + 1 ; print (i,'|' ,each) empty = []print ('打印empty列表' ,empty)print ("对member列表进行操作" )print ("使用append()方法插入新元素‘F’" ) member.append('F' )print (member[5 ]) print ('member的长度为:' ,len (member))print ('使用extend()方法插入新元素‘G’‘H’' ) member.extend(['G' ,'H' ])print ('member' ,member,'的长度为:' ,len (member)) i,j = 1 ,0 letter = "abcdefgh" while i < (len (member)+1 ): member.insert(i,letter[j]) i += 2 j +=1 print ('插入小写字母后的member列表:\n' ,member)
输出如下:
打印member列表:
['A', 'B', 'C', 'D', 'E']
打印mix列表:
位置 | 元素
1 | 1
2 | 二
3 | 3.14
4 | [1, 2, 3]
打印empty列表 []
对member列表进行操作
使用append()方法插入新元素‘F’
F
member ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] 的长度为: 8
插入小写字母后的member列表
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h']
操作符在列表中的应用 列表常见的一下操作符运算
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 numlist1 = [123 ] numlist2 =[456 ] numlist1 < numlist2 numlist3 = ['123' ,'456' ] numlist4 = ['456' ,'123' ] numlist3 == numlist4 numlist3 < numlist4 numlist5 = ['123' ,'456' ] numlist3 == numlist5 list1 = [123 ] list2 = [234 ] list1.extend(list2) list1 list1*3 list1*=3 list1 111 not in list1 123 in list1 mixlist = ['小明同学' ,['小红' ,'李华' ],456 ]'小明同学' in mixlist '小红' in mixlist mixlist[1 ][1 ]
列表中常见的一些逻辑操作符使用dir(list)
可以查看list的方法和内置函数:
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
方法名
操作
append
在末尾添加元素
clear
清除列表
copy
复制
count
统计元素
extend
添加
index
返回相应元素的下标
insert
插入元素
pop
删除并返回最后一个元素
remove
移除操作
reverse
翻转列表
sort
排序(递增)可以使用list1.sort(reverse=True)
进行降序排列 True可以改为1
1 2 3 4 5 6 7 8 9 10 11 12 13 list1.count(123 ) list1.index(123 ) list1.index(123 ,3 ,7 ) list3 = [23 ,34 ,654 ,876 ,123 ,1 ] list3.sort() list3 list3.sort(reverse=True ) list3
列表中的深拷贝与浅拷贝 可以看到等号进行的浅拷贝,相当于有一个指针指向了list3,而list5则是单独开辟了一块空间进行存储
1 2 3 4 5 6 list5 = list3[:] list6 = list3 list3.sort() list3 list5 list6
附带操作 1 2 3 4 list3 = [23 ,34 ,654 ,876 ,123 ,1 ]max (list3) min (list3) sum (list3)
4、元组和列表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 tuple1 = 1 ,2 ,4 ,5 ,6 print (tuple1) list1 = [1 ,2 ,4 ,5 ,6 ]print (list1) list1 = list1[:2 ] + [3 ] + list1[2 :] print ('插入元素之后的列表和元组\n' ,list1) tuple1 = tuple1[:2 ] + (3 ,) + tuple1[2 :] print (tuple1) temp = tuple1[:]del temp tuple2 = 2 *tuple1
(1, 2, 4, 5, 6)
[1, 2, 4, 5, 6]
插入元素之后的列表和元组
[1, 2, 3, 4, 5, 6]
(1, 2, 3, 4, 5, 6)
元组的操作符使用和列表 一致。
5、字符串 str字符串的一些方法:
方法名
用法
capitalize()
大写单词首字母
casefold()
小写所有字母
center()
居中字符串
count(sub[,start,end]) # [] 表示可选
统计start到end区间的sub字符串个数
encode(encoding = ‘utf-8’,errors=’strict’)
编码设置
espandtabs([tabsize=8])
把字符串中的\t 都替换成空格,可设置替换的空格数量
endswith(sub[,start,end])
判断是否以sub字符串结尾
find(sub[,start,end])
检测sub是否包含在字符串中,如果有则返回索引值,否则返回-1.start和end参数表示范围,可选
index(sub[,start,end])
和find基本一致,但是如果sub不在string0中则会产生一个异常
isalnum()
如果字符串中至少有一个字母并且全都是字母或数字则返回True,否则返回False
isalpha()
如果字符串中至少有一个字母并且全都是字母则返回True,否则返回False
isdigit()
如果字符串中只包含数字则返回True,否则返回False
islower()
如果字符串可以区分大小写,并且都是小写,则返回Ttrue,否则返回False
isnumeric()
如果字符中是包含数字,则返回True,否则False
isspace()
如果字符只包含空格,则返回True,否则False
istitle()
所有单词开头字母是大写就返回True,否则返回False
isupper()
如果字符串可以区分大小写,并且都是大写,则返回Ttrue,否则返回False
join(sub)
以字符串为分隔符插入到sub中所以的字符之间
ljust()
左对齐
strip()
去掉前后的空格,对应的还有lstrip()、rstrip(),分别是去掉左边和右边的空格
partition(sub)
以sub字符串为分界符,把字符串划分为一个三元组,默认返回一个元组;如果字符串中不包含sub,则返回('原字符串','','')
replace(old,new[,count])
替换字符串,如果指定count,则只替换指定次数
split(sep=None,maxsplit=-1)
不带参数默认是以空格为分解符切片字符串,如果maxsplit参数有设置,则仅分割maxsplit个子字符串,返回切片后的字符串列表
startswith(sub[,start,end])
title()
translate()
根据table的规则(可以由str.maketrans('a','d')
定制)转换字符串中的字符
upper()
将所有字母都大写
zfill(lenght)
返回指定长度的字符串,如果原字符串不够,则前边用0代替
代码示例: 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 name = " ada lovelace " name' ada lovelace ' name[:4 ]' ada' name.rstrip() name.lstrip() name.strip() name.strip().capitalize() 'Ada lovelace' NAME = 'ADA LOVELACE' NAME.casefold()'ada lovelace' name.center(40 )' ada lovelace ' name.count('a' )3 name.endswith('' )True name.endswith('lace' )False name.find('ada' )1 name.find('cda' ) -1 name.join('||||||' )'| ada lovelace | ada lovelace | ada lovelace | ada lovelace | ada lovelace |' listName = name.partition('love' ) listName (' ada ' , 'love' , 'lace ' )type (listName) <class 'tuple' > name.replace('ada' ,'dad' )' dad lovelace ' name.split() ['ada' , 'lovelace' ] name.translate(str .maketrans('a' ,'b' ))' bdb lovelbce ' name.title()' Ada Lovelace ' name.upper()' ADA LOVELACE ' name.zfill(40 )'00000000000000000000000000 ada lovelace '
字符串格式化 format()
的用法:
1 2 3 4 5 6 7 8 9 10 11 "{0},{1}{2}" .format (" ada" ," love" ,"lace " )' ada, lovelace ' "{a}{b}{c}" .format (a=" ada " ,b="love" ,c="lace " )' ada lovelace ' "{{0}}" .format ("不打印" )'{0}' '{0:.1f}{1}' .format (3.1415 ,'GB' )'3.1GB'
字符串格式化符号含义
符号
说明
%c
格式化字符及其ASCII码
%s
格式化字符串
%d
格式化整数
%o
格式化无符号八进制数(octonary,OCT)
%x
格式化无符号十六进制数
%f
格式化无符号十六进制数(大写)
%e
格式化定点数,可指定小数点后的精度
%E
用作科学技术法格式化定点数
%g
根据值的大小决定%f或%e
%G
作用同%g,根据值的大小决定使用%f或者%e
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 letter = '%c %c %c' % (97 ,98 ,99 ) letter'a b c' name = '%s' % 'ada lovelace' name'ada lovelace' '%f' % 3.1415 '3.141500' '%#x' % 18 '0x12'
格式化操作辅助命令
符号
说明
m.n
m是显示的最小总宽度,n是小数点后的位数
-
用于左对齐
+
在正数前面显示加号(+)
#
在八进制数前面显示零(‘0’),在十六进制数前面显示’0x’或者’0x’
0
显示的数字前面填充’0’取代空格
1 2 3 4 5 6 7 8 9 10 '%+1.2f' % 3.1415 '+3.14' '%-10.2f' % 3.1415 '3.14 ' '%#x' % 18 '0x12' '%#X' % 18 '0X12'
字符串转义字符含义
符号
说明
\‘
单引号
\“
双引号
\a
发出系统响铃声
\b
退格符
\n
换行符
\t
横向制表符
\v
纵向制表符
\r
回车符
\f
换页符
\o
八进制数代表的字符
\x
十六进制数代表的字符
\0
表示一个字符
\\
反斜杠
列表、元组、字符串小结 列表、元组和字符串的共同点:
都可以通过索引得到每一个元素
默认索引值总是从0开始
可以通过分片的方法得到一个范围内的元素的集合
有很多共同的操作符(无重复操作符、拼接操作符、成员关系操作符)
6、序列 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 name = "ada lovelace" name = list (name) print (name)print (min (name)) print (max (name)) tupleNum = (1 ,2 ,3 ,4 ,5 ,6 )print (max (tupleNum)) tupleNum = (1 ,2 ,3 ,4 ,5 ,6 ,'A' ) tupleNum2 = (2 ,3 ,1 ,5 ,4 )print ('tupleNum2:' ,tupleNum2)print ('sun(tupleNum2):' ,sum (tupleNum2))print ('sorted()排序之后:' ,sorted (tupleNum2))print ('reversed()函数调用:' ,reversed (tupleNum2))print ('list(reversed(tumpleNum2))):' ,list (reversed (tupleNum2)))enumerate (tupleNum2)print ('list(enumerate(tupleNum2)):' ,list (enumerate (tupleNum2)))print ('tupleNum和tupleNum2:' ,tupleNum,tupleNum2)print ('list(zip(tupleNum,tupleNum2)):' ,list (zip (tupleNum,tupleNum2)))
上述运行结果:
['a', 'd', 'a', ' ', 'l', 'o', 'v', 'e', 'l', 'a', 'c', 'e']
v
6
tupleNum2: (2, 3, 1, 5, 4)
sun(tupleNum2): 15
sorted()排序之后: [1, 2, 3, 4, 5]
reversed()函数调用:
list(reversed(tumpleNum2))): [4, 5, 1, 3, 2]
list(enumerate(tupleNum2)): [(0, 2), (1, 3), (2, 1), (3, 5), (4, 4)]
tupleNum和tupleNum2: (1, 2, 3, 4, 5, 6, 'A') (2, 3, 1, 5, 4)
list(zip(tupleNum,tupleNum2)): [(1, 2), (2, 3), (3, 1), (4, 5), (5, 4)]
7、函数 使用def
创建函数
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 def MyFirstFunction (): print ("调用了MyFirstFunction()函数" ) print ("函数创建格式是 \'def 函数名():\'" ) MyFirstFunction()def PrintName (name ): print ('我的名字是:' ,name) PrintName('mingming' )def add (num1,num2 ): return (num1+num2)sum = add(5 ,10 )print (sum )def printName (name = 'ada lovelace' ): print (name)print ()def collaction (*parameters ): print ('参数的长度是:' ,len (parameters)) print ("第二个参数是:" ,parameters[1 ]) collaction('a' ,'b' ,'c' )
上述代码运行结果:
调用了MyFirstFunction()函数
函数创建格式是 'def 函数名():'
我的名字是: mingming
15
ada lovelace
参数的长度是: 3
第二个参数是: b
函数返回值 在python中函数会自动为没有返回值的函数返回None
1 2 3 def letterList (): return ['A' ,'B' ,'C' ]
输出['A', 'B', 'C']
函数变量的作用域 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def discount (price,rate ): final_price = price * rate old_price = 1000 return final_price old_price = float (input ('请输入原价:' )) rate = float (input ('请输入折扣:' ))print ('打折后的价格是:' )print (discount(old_price,rate)) pritn(old_price)
程序输入:
100
0.8
程序输出:
这里是对全局变量修改后的值 50.0
80.0
old_price修改后的值: 50.0
函数嵌套 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def fun1 (): print ('fun1函数正在被调用' ) def fun2 (): print ('fun2函数正在被调用' ) fun2() fun1()def FunX (x ): def FunY (y ): return x*y return FunY Funx(2 )(5 )
在闭包中:外层的局部变量对内层而言也是不可以使用的,可以通过容器实现值传递。如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def fun1 (): x = 5 def fun2 (): x *= x return x return fun2()def fun1 (): x = [5 ] def fun2 (): x[0 ] *= x[0 ] return x[0 ] return fun2()def fun1 (): x = 5 def fun2 (): nonlocal x x *= x return xreturn fun2()
8、lambda表达式 使用lambda表达式创建匿名函数,使用lambda表达式有以下优势:
筛选器filter
使用filter筛选器对字段进行筛选
1 2 3 4 5 6 7 8 9 10 temp = range (1 ,10 )def odd (x ): return x % 2 ; show = filter (odd,temp)print (list (show))list (filter (lambda x : x % 2 ,range (10 ))) list (map (lambda x : x **2 ,range (10 ))) [0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 ]
9、递归 实例一:阶乘 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def factorial (n ): result = n for i in range (1 ,n): result *= i return resultdef recurisionFac (n ): if n != 1 : return n * recurisionFac(n-1 ) else : return 1 num = int (input ('请输入一个正整数:' ))print ('%d的阶乘是%d' %(num,recurisionFac(num)))
实例二:斐波那契数列 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def fibonaq (n ): if n == 1 or n == 2 : return 1 else : return fibonaq(n-1 )+fibonaq(n-2 )print (fibonaq(10 ))def fab (n ): n1 = 1 n2 = 1 n3 = 2 while n > 2 : n3 = n2 + n1 n1 = n2 n2 = n3 n -= 1 return n3
实例三、汉诺塔 1 2 3 4 5 6 7 8 9 10 def hanoi (n,x,y,z ): if n == 1 : print (x,'--->' ,z) else : hanoi(n-1 ,x,z,y) print (x,'---->' ,z) hanoi(n-1 ,y,x,z) n = int (input ('请输入汉诺塔的层数:' )) hanoi(n,'X' ,'Y' ,'Z' )
10、字典{} 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 brand = ['李宁' ,'安踏' ,'耐克' ,'阿迪' ] slogn = ['A' ,'B' ,'C' ,'D' ]print ('阿迪对应的的letter是:' ,slogn[brand.index('阿迪' )]) dict1 = {'李宁' :'A' ,'安踏' :'B' ,'耐克' :'C' ,'阿迪' :'D' }print ('阿迪对应的letter是(2):' ,dict1['阿迪' ]) dict3 = dict ((('F' ,70 ),('B' ,15 ),('C' ,90 ),('S' ,123 )))print (dict3) dictEmp = {} dictEmp.fromkeys((1 ,2 ,3 )) dictEmp = dictEmp.fromkeys(range (32 ),'赞' ) dictEmp[4 ] = '不赞' dictcopy = dictEmp.copy()print ('打印拷贝字典:' ,dictcopy) dictEmp.setdefault('最后位置' ) dictEmp.setdefault(32 ,'第32个位置' )print (dictEmp)print (dictEmp.pop(4 ))print (dictEmp.popitem()) dictEmp.clear()print (dictEmp)
11、文件 open()函数原型
Open file and return a stream. Raise OSError upon failure.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
mode的参数:
打开方式
执行操作
r
以只读方式打开文件(默认)
w
以写入的当时打开文件
x
会覆盖已存在的文件
a
如果文件已经存在,使用此模式打开将引发异常
b
以写入模式打开,如果文件存在,则在末尾追加写入
t
以文本模式打开
+
可读写模式(可添加到其他模式中使用)
U
通用换行符支持
code:
1 2 3 4 Datafile = open ('D:\\Groceries.csv' ) Datafile Datafile.close()
文件对象方法
文件对象方法
执行操作
f.close()
关闭文件
f.read(size=-1)
从文件读取size个字符,当未给定size或给定负值是,读取剩余的所有字符,然后作为字符串返回
f.readline()
以写入模式打开,如果文件存在,则在末尾追加写入
f.write(str)
将字符串str写入文件
f.writelines(seq)
向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象
f.seek(offset,from)
在文件中移动文件指针,从from(0代表起始位置,1代表当前位置,2代表文件末尾)偏移offset个字节
f.tell()
返回当前在文件中的位置
12、集合set 在我的世界里,你就是唯一,set()集合中只允许同值数据出现一次。:rescue_worker_helmet:
1 2 3 4 for i in range (0 ,5 ): temp.append(i) temp.append(1 ) temp2 = list (set (temp)) temp2 = [0 ,1 ,2 ,3 ,4 ]
小甲鱼29:一个任务的代码
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 f = open ('record.txt' ) boy = [] girl = []for each_line in f: if each_line[:6 ] != '=======' : (role,line_spoken) = each.split(':' ,1 ) if role == '小甲鱼' : boy.append(line_spoken) if role == '小客服' : girl.append(line_spoken) else : file_name_boy = 'boy_' + str (count) + '.txt' file_name_boy = 'girl_' + str (count) + '.txt' boy_file = open (file_name_boy,'w' ) girl_file = open (file_name_girl,'w' ) boy_file.writelines(boy) girl_file.writelines(girl) boy = [] girl = [] count += 1 file_name_boy = 'boy_' + str (count) + '.txt' file_name_boy = 'girl_' + str (count) + '.txt' boy_file = open (file_name_boy,'w' ) girl_file = open (file_name_girl,'w' ) boy_file.writelines(boy) girl_file.writelines(girl) boy_file.close() girl_file.close()
以上代码冗长繁琐,不够简洁,因此可以对关键部分进行封装:
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 def save_file (boy,girl,count ): file_name_boy = 'boy_' + str (count) + '.txt' file_name_boy = 'girl_' + str (count) + '.txt' boy_file = open (file_name_boy,'w' ) girl_file = open (file_name_girl,'w' ) boy_file.writelines(boy) girl_file.writelines(girl) boy_file.close() girl_file.close()def split_file (file_name ): f = open (file_name) boy = [] girl = [] for each_line in f: if each_line[:6 ] != '=======' : (role,line_spoken) = each.split(':' ,1 ) if role == '小甲鱼' : boy.append(line_spoken) if role == '小客服' : girl.append(line_spoken) else : save_file(boy,girl.count) boy = [] girl = [] count += 1 split_file('record.txt' )
13、模块 os模块 os模块中关于文件/目录常用的函数使用方法
函数名
使用方法
getcwd()
返回当前工作目录
chdir(path)
改变工作目录
listdir(path=’.’)
列举指定目录中的文件名(’.’表示当前目录,’..’表示上一级目录)
mkdir(path)
创建单层目录,如该目录已存在抛出异常
makedirs(path)
递归创建多层目录,如该目录已存在抛出异常,注意:’E:\a\b’和’E:\a\c’并不会冲突
remove(path)
删除文件
rmdir(path)
删除单层目录,如该目录非空则抛出异常
removedirs(path)
递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常
rename(old, new)
将文件old重命名为new
system(command)
运行系统的shell命令
walk(top)
遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])【具体实现方案请看:第30讲课后作业^_^】
以下是支持路径操作中常用到的一些定义,支持所有平台
os.curdir
指代当前目录(’.’)
os.pardir
指代上一级目录(’..’)
os.sep
输出操作系统特定的路径分隔符(Win下为’\‘,Linux下为’/‘)
os.linesep
当前平台使用的行终止符(Win下为’\r\n’,Linux下为’\n’)
os.name
指代当前使用的操作系统(包括:’posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’)
os.path模块中关于路径常用的函数使用方法
函数名
使用方法
basename(path)
去掉目录路径,单独返回文件名
dirname(path)
去掉文件名,单独返回目录路径
join(path1[, path2[, …]])
将path1, path2各部分组合成一个路径名
split(path)
分割文件名与路径,返回(f_path, f_name)元组。如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在
splitext(path)
分离文件名与扩展名,返回(f_name, f_extension)元组
getsize(file)
返回指定文件的尺寸,单位是字节
getatime(file)
返回指定文件最近的访问时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
getctime(file)
返回指定文件的创建时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
getmtime(file)
返回指定文件最新的修改时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
以下为函数返回 True 或 False
exists(path)
判断指定路径(目录或文件)是否存在
isabs(path)
判断指定路径是否为绝对路径
isdir(path)
判断指定路径是否存在且是一个目录
isfile(path)
判断指定路径是否存在且是一个文件
islink(path)
判断指定路径是否存在且是一个符号链接
ismount(path)
判断指定路径是否存在且是一个挂载点
samefile(path1, paht2)
判断path1和path2两个路径是否指向同一个文件
1 2 3 4 5 6 7 os.mkdir('E:\\A' ) os.getcwd().split() ['C:\\Users\\明明\\PycharmProjects\\StudyFirstDay' ] os.getcwd().split('\\' ) ['C:' , 'Users' , '明明' , 'PycharmProjects' , 'StudyFirstDay' ] os.getcwd().split('\\' )[2 ]'明明'
pickle
模块下面代码上和通过pkl文件把my_list
列表读取到my_list2
1 2 3 4 5 6 7 my_list = [123 ,3.14 ,'小甲鱼' ,['another list' ]] pickle.dump(my_list,pickle_file) pickle_file.close() pickle_file=open ('my_list.pkl' ,'rb' ) my_list2 = pickle.load(pickle_file)print (my_list2)>>> [123 , 3.14 , '小甲鱼' , ['another list' ]]
14、异常 Python标准异常总结
AssertionError
断言语句(assert)失败
AttributeError
尝试访问未知的对象属性
EOFError
用户输入文件末尾标志EOF(Ctrl+d)
FloatingPointError
浮点计算错误
GeneratorExit
generator.close()方法被调用的时候
ImportError
导入模块失败的时候
IndexError
索引超出序列的范围
KeyError
字典中查找一个不存在的关键字
KeyboardInterrupt
用户输入中断键(Ctrl+c)
MemoryError
内存溢出(可通过删除对象释放内存)
NameError
尝试访问一个不存在的变量
NotImplementedError
尚未实现的方法
OSError
操作系统产生的异常(例如打开一个不存在的文件)
OverflowError
数值运算超出最大限制
ReferenceError
弱引用(weak reference)试图访问一个已经被垃圾回收机制回收了的对象
RuntimeError
一般的运行时错误
StopIteration
迭代器没有更多的值
SyntaxError
Python的语法错误
IndentationError
缩进错误
TabError
Tab和空格混合使用
SystemError
Python编译器系统错误
SystemExit
Python编译器进程被关闭
TypeError
不同类型间的无效操作
UnboundLocalError
访问一个未初始化的本地变量(NameError的子类)
UnicodeError
Unicode相关的错误(ValueError的子类)
UnicodeEncodeError
Unicode编码时的错误(UnicodeError的子类)
UnicodeDecodeError
Unicode解码时的错误(UnicodeError的子类)
UnicodeTranslateError
Unicode转换时的错误(UnicodeError的子类)
ValueError
传入无效的参数
ZeroDivisionError
除数为零
异常捕捉 1 2 3 4 try : 检测范围except Exception[as reason]: 出现异常(Exception)后的处理代码
Testdemo📝:
1 2 3 4 5 6 7 8 9 try : f = open ('一个文件.txt' ) print (f.read()) f.close()except OSError as reason: print ('文件出错了,错误的原因是:' ,str (reason))except TypeError as reason: print ('类型出错了,错误的原因是:' ,str (reason))
finanlly关键字:
1 2 3 4 5 6 7 8 9 10 11 try : sum = 1 + '1' f = open ('一个文件.txt' ) print (f.read()) f.close()except OSError as reason: print ('文件出错了,错误的原因是:' ,str (reason))except TypeError as reason: print ('类型出错了,错误的原因是:' ,str (reason))finally : print ('执行备用方案' )
额外补充📚:
raise #该关键字可以将系统错误自定义设置
15、对象 定义一个简单的类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class People : name = '空白' age = 10 def setName (self,name ): self.name = name def getName (self ): print ('我是' +self.name) p = People() p.getName() p.setName('小明' ) p.getName()
构造函数 1 2 3 4 5 class People : def _init_ (self,name ): self.name = name p1 = People("HR" )
公有与私有 Python中使用name mangling
实现访问机制
1 2 3 4 5 6 7 8 class People : __name = "Programmer" def getName (self ): return self.__name p = People() p.__name p.getName()
继承 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Parent : def __init__ (self ): self.number = rd.randint(0 ,10 ) print ("正在调用父类构造方法" )class Child (Parent ): def __init__ (self ): Parent.__init__() print ("正在调用子类构造方法" ) pass p = Parent() p.__init__() c = Child()
super()函数
1 2 就是在子类的构造函数中,使用super ().__init__()
多继承 1 2 3 4 5 6 7 8 9 10 11 class A : def __init__ (self,name ): self.name = nameclass B : def __init__ (self,name ): self.name = nameclass C (A,B): def __init__ (self,nameA,nameB ): a = self.A(nameA) b = self.b(nameB) print ("我是" +a.name+"和" +b.name+"的儿子" )
拾遗 1 2 3 4 5 6 7 8 9 10 11 12 class A : def __init__ (self,name ): self.name = nameclass B : def __init__ (self,name ): self.name = nameclass C (A,B): def __init__ (self,nameA,nameB ): self.a = A(nameA) self.b = B(nameB) print ("我是" +self.a.name+"和" +self.b.name+"的儿子" ) c = C("A" ,"B" )