Python基础学习笔记
-
原始字符串 str = r’\n\\t’,输出为\n\\t,在前面加r表示字符串不认识转义字符,将其看成一般的字符进行输出
-
三引号的作用:用作多行注释,用作字符串里面不需要换行字符如:
"""日期:2021/1/25 作者:李佳宇""" str01 = """李佳宇 长沙理工大学 软件1803""" str02 = "李佳宇\n" \ "长沙理工大学\n" \ "软件1803" if __name__ == '__main__': print(str01) print(str02)
输出结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZUMepeZU-1611732022034)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210125135123671.png)]
-
i = 15e10 #表示150000000000.0,用e实现科学计数法
-
float()方法将字符串变为浮点数,str() 方法转换为字符串,isinstance(参数,数据类型) 判断参数是否为某个数字类型
-
bool类型的值可以进行加减法,其中True的值为1,False的值为0
print(not 1) #结果为: False print(not 123) #结果为: False print(not 0) #结果为: True
-
一个(/)相当于正常的计算,两个(//)相当于java中除法的运算,两个(**)相当指数运算
print(10 / 8) #结果为: 1.25 print(10 // 8) #结果为: 1 print(3 ** 5) #结果为: 243
-
python支持多个数比较
print(1<2<3) #结果为: True print(1<2>3) #结果为: False
-
python三元操作符
x = 1 y = 0 small = x if x<y else y # 相当于java中small = x<y?x:y print(small) #结果为0
-
assert关键字,当这个关键字后边的条件为假的时候,程序自动崩溃并抛出异常,一般用它在程序中置入检查点
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZQ5cq9OO-1611732022043)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210125154019061.png)]
输出结果:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rjcRfocd-1611732022049)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210125154041846.png)]
-
range() 的使用
print(list(range(5))) #结果为: [0, 1, 2, 3, 4] print(list(range(1,5))) #结果为: [1, 2, 3, 4] print(list(range(0,5,2))) #结果为: [0, 2, 4] print(list(range(5,0,-1))) #结果为: [5, 4, 3, 2, 1]
-
python列表:普通列表,混合列表和空列表
common = [1,2,3,4,] print(common) #结果为: [1, 2, 3, 4] mix = [1,"2",3.0,[4]] print(mix) #结果为: [1, '2', 3.0, [4]] empty = [] print(empty) #结果为: []
向列表末尾添加元素的方法:append()
向列表末尾添加列表的方法:extend()
向列表中添加元素的方法:insert()
其他的常用方法:
empty = []
empty.append(3)
print(empty)
empty.insert(0,'2')
print(empty)
empty.extend([4,2])
print(empty)
print(empty.index('2'))
empty.remove('2')
print(empty)
print(len(empty))
empty.sort() #empty.sort(reverse=True)实现大到小排序
print(empty)
empty.reverse()
print(empty)
empty.pop(0) #(1)等同于del empty[0](2)pop()函数不传参数时取出最后一个元素
print(empty)
empty.append([5,6])
print(empty)
print(2 not in empty)
print(5 in empty)
"""
输出结果为:
[3]
['2', 3]
['2', 3, 4, 2]
0
[3, 4, 2]
3
[2, 3, 4]
[4, 3, 2]
[3, 2]
[3, 2, [5, 6]]
False
False
"""
列表分片:
print(empty)
print(empty[1:3])
print(empty[1:])
print(empty[:3])
print(empty[1::2])
print(empty[::-1])
print(empty[-3:-1])
print(empty[-1:-3])
print(empty[-4:-1:2])
"""
输出结果为:
[1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[1, 2, 3]
[2, 4]
[4, 3, 2, 1]
[2, 3]
[]
[1, 3]
"""
-
python元组,同列表一样,元组能用()创建一个空元组,能用[]访问到元素,能用[:]进行分片操作,但是元组不能随便修改元素,添加元素和删除元素,如以下操作就会报错:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zz3VVfXl-1611732022053)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210125173639242.png)]
元组的创建为:
tuple01 = 1,2,3 print(tuple01) tuple02 = 1, print(tuple02) tuple03 = 8 * (8) print(tuple03) tuple04 = 8 * (8,) print(tuple04) """ 结果为: (1, 2, 3) (1,) 64 (8, 8, 8, 8, 8, 8, 8, 8) """
元组元素的添加可以通过分片实现:
print(tuple01) tupleNew = tuple01[:1] + (1.5,) + tuple01[1:] # 注意1.5后面的逗号必不可少 print(tupleNew) """ 运行为: (1, 2, 3) (1, 1.5, 2, 3) """
-
python字符串,同列表一样,字符串能用""创建一个空字符串,能用[]访问到指定字符,能用[:]进行分片操作,但是同元组一样,不能随便修改字符,添加字符和删除字符
字符串的常用方法有:
str2 = "this is a string" str2 = str2.capitalize() # 将字符串第一个字符变为大写 print(str2) str2 = str2.casefold() # 将所有字符变为小写 print(str2) str2 = str2.center(20) # 将字符串居中,两边用" "补充 print(str2) print(str2.count("is")) # 计算指定内容出现次数 str2 = str2.replace(" ","\t") # 替换指定内容为新内容 print(str2) str2 = str2.expandtabs(0) # 将字符串的\t转换为空格,不传参数空格数为8 print(str2) print(str2.endswith("ing")) # 判断字符串是否以指定内容结尾 print(str2.isalpha()) # 判断字符串是不是只包含字母 str2 = str2.join("--") # 将字符串插入指定字符串中 print(str2) str2 = str2.rjust(20) # 右对齐 print(str2) str2 = str2.lstrip(" ") # 去除左侧指定字符 print(str2) print(str2.find("th")) # 查找字符 str2 = str2.split("is") # 字符串按照指定内容切割 print(str2) """ 运行结果: This is a string this is a string this is a string 2 this is a string thisisastring True True -thisisastring- -thisisastring- -thisisastring- 1 ['-th', '', 'astring-'] """
字符串的格式化:
str3 = "{0} love {1}".format("I","js") print(str3) str4 = "{a} love {b}".format(a="I", b="java") print(str4) str5 = "{0} love {a}".format("I", a="python") print(str5) str6 = "{{0}}".format("不打印") # 表转义 print(str6) str7 = '{0:5.1f}'.format(27.374) #小数点左边为数的宽度,小数点右边为数的精度 print(str7) str8 = '{0:10d}'.format(123) print(str8) str9 = '%c%-5d%s %.1f %g %x' % ('o',666,"ljy",1.1,1.10,10) # %g灵活是%f的加强版,可以灵活使用%f print(str9) str10 = '%#o' % 11 #八进制 print(str10) str10 = '%#X' % 11 # 十六进制,小写的x即字母也用小写表示 print(str10) """ 运行结果: I love js I love java I love python {0} 27.4 123 o666 ljy 1.1 1.1 a 0o13 0XB """
-
python序列包括列表,元组和字符串,其共同点有:
- 都可以通过索引得到每一个元素
- 可以通过分片的方法得到一个范围内的元素的集合
- 有很多共同的操作符(重复操作符,拼接操作符和成员关系操作符)
序列的内置函数有:
list() 将一个可迭代对象转换为一个列表
tuple() 将一个可迭代对象转换为一个元组
str() 将一个对象转换为字符串
len() 返回长度
max() 返回序列中ascII最大值
min() 返回序列中ascII最小值
sum() 返回序列每一个元素的和
sorted() 返回一个排序好的列表
reversed() 返回一个倒置的对象
enumerate() 返回一个枚举的对象
zip() 返回一个打包的对象
tuple1 = (1,-32,4,23,-5,0) tuple1 = tuple(sorted(tuple1)) print(tuple1) tuple1 = tuple(reversed(tuple1)) print(tuple1) tuple1 = tuple(enumerate(tuple1)) print(tuple1) tuple2 = tuple1[:1] + (1,) + tuple1[1:] tuple1 = tuple(zip(tuple1,tuple2)) print(tuple1) """ 运行结果: (-32, -5, 0, 1, 4, 23) (23, 4, 1, 0, -5, -32) ((0, 23), (1, 4), (2, 1), (3, 0), (4, -5), (5, -32)) (((0, 23), (0, 23)), ((1, 4), 1), ((2, 1), (1, 4)), ((3, 0), (2, 1)), ((4, -5), (3, 0)), ((5, -32), (4, -5))) """
-
函数文档在函数明下面由单引号包括
def test(): 'test函数文档' print("test") print(test.__doc__) # 输出结果为:test函数文档 help(print) # 输出内置函数的函数文档
-
global 关键字可以在函数内部修改函数外部的变量
i = 1 def test01(): global i i = 2 test01() print(i) # 输出为:2
-
闭包
def funX(x): def funY(y): return x*y return funY i = funX(3) print(type(i)) # 输出结果为<class 'function'> j = i(4) print(j) # 输出结果为12
-
nonlocal关键字
def fun1(): xi = 5 def fun2(): nonlocal xi xi *= xi return xi return fun2() i = fun1() print(i) # 输出结果为:25
nonlocal与global的区别:
第一,两者的功能不同。global关键字修饰变量后标识该变量是全局变量,对该变量进行修改就是修改全局变量,而nonlocal关键字修饰变量后标识该变量是上一级函数中的局部变量,如果上一级函数中不存在该局部变量,nonlocal位置会发生错误(最上层的函数使用nonlocal修饰变量必定会报错)。
第二,两者使用的范围不同。global关键字可以用在任何地方,包括最上层函数中和嵌套函数中,即使之前未定义该变量,global修饰后也可以直接使用,而nonlocal关键字只能用于嵌套函数中,并且外层函数中定义了相应的局部变量,否则会发生错误。
-
filter过滤器和map函数的区别:
filter返回true值
map是每一个结果都返回
def odd(x): return x%2 print(list(filter(odd,range(10)))) # 奇数过滤器 print(list(filter(lambda x: x % 2,range(10)))) # 使用lambda的奇数过滤器 print(list(filter(lambda x:not x % 2, range(10)))) # 使用lambda的偶数过滤器 print(list(map(lambda x:x*2,range(10)))) # map函数根据提供的函数对指定序列做映射
-
python字典用大括号表示,键值对中间用 : 分开,字典创建的方法有:
dict1 = {"李宁":"一切皆有可能","Nike":"Just do it","阿迪达斯":"Nothing is impossible"} print(dict1["李宁"]) dict2 = {} # 创建一个空字典 print(dict2) dict3 = dict(((65,"a"),(66,"B"),(67,"C"))) print(dict3) dict3[65] = "A" # 如果有就更新 dict3[68] = "D" # 如果没有就添加一个新的键值对 print(dict3) dict4 = dict(b="B",a="A") print(dict4["b"]) print(dict4) dict5 = dict([(68,"D"),(69,"E"),(70,"F")]) #与dict3查不多,只要构成映射关系即可 print(dict5) /* 运行结果: 一切皆有可能 {} {65: 'a', 66: 'B', 67: 'C'} a {65: 'A', 66: 'B', 67: 'C', 68: 'D'} B {'b': 'B', 'a': 'A'} {68: 'D', 69: 'E', 70: 'F'} */
字典常用方法:
print(dict5.fromkeys((1, 2, 3))) # fromkeys创建并返回一个新的字典,默认值为None print(dict5.fromkeys((1,2,3),('a','b','c'))) # 创建并返回了值 print(dict5) print(dict5.keys()) # 获取键 for eachkey in dict5.keys(): print(eachkey,end=" ") print() print(dict5.values()) # 获取值 for eachvalue in dict5.values(): print(eachvalue,end=" ") print() print(dict5.items()) # 获取键值对 for eachitem in dict5.items(): print(eachitem,end=" ") print() print(dict5.get(3)) print(dict5.get(3,"没有这个键")) # 使用get函数比直接访问如dict5[3]更安全 print(3 in dict5) # 判断字典中是否存在某个键 dict6 = dict5 dict5 = {} # 将dict5指向一个新的空字典,dict6不会该改变 print(dict5) print(dict6) dict5 = dict6 dict6.clear() # 清空字典方法 print(dict5) print(dict6) dict7 = dict4.copy() # 浅拷贝 print(id(dict7)) print(id(dict4)) print(dict7) print(dict7.popitem()) # 随机弹出一个键值对 print(dict7) print(dict4.pop('a')) # 指定弹出某个键值对 dict7.setdefault('a','A') print(dict7) # 字典中没有顺序 dict8 = {'b':'BB'} dict7.update(dict8) # 字典更新数据 print(dict7) """ 运行截图: {1: None, 2: None, 3: None} {1: ('a', 'b', 'c'), 2: ('a', 'b', 'c'), 3: ('a', 'b', 'c')} {68: 'D', 69: 'E', 70: 'F'} dict_keys([68, 69, 70]) 68 69 70 dict_values(['D', 'E', 'F']) D E F dict_items([(68, 'D'), (69, 'E'), (70, 'F')]) (68, 'D') (69, 'E') (70, 'F') None 没有这个键 False {} {68: 'D', 69: 'E', 70: 'F'} {} {} 2674403144128 2674397191744 {'b': 'B', 'a': 'A'} ('a', 'A') {'b': 'B'} A {'b': 'B', 'a': 'A'} {'b': 'BB', 'a': 'A'} """
-
python集合也用大括号表示,集合创建和常用的方法有:
set01 = set([5,4,3,2,1,1,2,3,4,5]) # 集合是无序的 print(set01) set02 = frozenset([6,7,6,7]) # 集合元素不能随便该改变 print(set02) set03 = {1,2,3,4,5,5} print(set03) set01.add(6) # 向集合中添加数据 print(set01) set01.add(set02) # 错误使用方法,在集合中添加一个集合 print(set01) set01.remove(set02) # 删除集合的一个指定元素 print(set01) set01.pop() # 随机删除集合的一个元素 print(set01) set01.discard(7) # 如果删除的元素存在,删除,不存在不做处理 print(set01) set01.update(set02) # 更新集合 print(set01) print(set01.intersection(set03)) # 取交集 print(set01 & set03) print(set01.union(set03)) # 取并集 print(set01 | set03) print(set01.difference(set03)) # 取差集 print(set01 - set03) print(set01.symmetric_difference(set03)) # 取补集 print(set01 ^ set03) """ 运行结果为: {1, 2, 3, 4, 5} frozenset({6, 7}) {1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 6} {1, 2, 3, 4, 5, 6, frozenset({6, 7})} {1, 2, 3, 4, 5, 6} {2, 3, 4, 5, 6} {2, 3, 4, 5, 6} {2, 3, 4, 5, 6, 7} {2, 3, 4, 5} {2, 3, 4, 5} {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7} {6, 7} {6, 7} {1, 6, 7} {1, 6, 7} """
-
python文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fGc50lrx-1611732022055)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210127104337485.png)]
fr = open("C:\\Users\\Administrator\\test.txt",'r') print(fr.readline()) # 打印一行内容 print(fr.tell()) # 打印当前在文件中的位置(中文一个占两个字节,换行符占两个2字节) fr.seek(2,0) # 第一个参数为移动位置,第二个参数为0时在文件头,为1时在当前位置,为2时在文件尾 print(fr.read()) # 打印剩下全部内容 f = open("C:\\Users\\Administrator\\test.txt",'r+') # r+:可读可写,若文件不存在,报错;w+:可读可写,若文件不存在,创建 for each_line in f: print(each_line,end="") f.write("\nnewline") # 写入数据,方法还有writelines() f.close()
-
文件操作
print(os.chdir("E:\\")) # 改变路径 print(os.getcwd()) # 获取当前路径 print(os.listdir("E:\\PythonProject\\study")) # 列举当前路径文件 f = open("E:\\PythonProject\\study\\temp.txt","a") # 创建文件 f.close() os.mkdir("E:\\PythonProject\\study\\first") # 创建文件夹 os.makedirs("E:\\PythonProject\\study\\second\\com\\ljy") # 递归创建多层目录 os.remove("E:\\PythonProject\\study\\temp.txt") # 删除文件 os.rmdir("E:\\PythonProject\\study\\first") # 删除目录,目录为空 # os.system("cmd") # 运行任务管理器
-
异常
try: i = 1/0 except Exception as reason: print("ERROR! "+str(reason)) finally: print("complete") """ 运行结果: ERROR! division by zero complete """
-
else和with的高阶用法
num = 11 count = num//2 while count>1: # for同样可以搭配else if num % count == 0: print('%d最大约数是%d' % (num,count)) break count -= 1 else: # 如果while正常执行完则执行,如果break退出执行则不执行 print('%d是素数' % num) try: print("") except: print("出错了") else: # 出现异常则不会执行else内的语句 print("没有错误") try: with open("E:\\PythonProject\\study\\study01.py",'w') as f: # 系统自动检测并关闭文件 for each_line in f: print(each_line) except Exception as reason: print(str(reason))