1. 基本语法
python为弱语言类型, 根据赋予的值决定具体数据类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 name = input ("inputyour name" ) print ("hi" , "im" , sep = "-" , end = "joke" )c = 11.5551 print ("%d" %c)print ("%.2f" %c) print ("%5.1f" %c)a = [1 ,2 ,3 ] print (type (a))
1.1 基本数据类型 int 类型
无大小限制, 内存许可就无限大
1 2 3 4 5 6 7 print (0b1101 ) print (0o734 ) print (0x81 ) print (bin (21 )) print (oct (21 )) print (hex (21 ))
float 类型
1 2 print (float (130 )) print (1.3e4 )
bool 类型
空字符串, 空数组, 空集合均为false
复数类型
1 2 3 4 5 6 7 a = 10 + 3j print (a)print (a.real, a.imag)print (complex (3 , 4 ))
字符串类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 a = "abcd" for i in a: print (i) print (a*3 )print (a+a)print (a[0 : 2 ]) print (a[::-1 ])
字符串常用函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 str = "aaBcD 123a" str .capitalize() print (str .find("13" )) print (str .index("1" )) str .lower() str .upper() print (str .split(" " )) print (str .strip("a" )) print (str ) a = 10 b = 30 b1 = 40 print (f"{a} + {b} = {a+b1} " )print (f"{a-3 } + {b} = {a+10 } " )
部分类型转换函数
1 2 3 4 5 6 7 8 9 10 11 print (int (1.2 )) print (chr (77 )) print (eval ("3 * 9" )) x = 10 ; y = 20 print (eval ("x * y" )) a = int (bin (16 ),2 ) b = int (oct (16 ),8 ) c = int ("aB234" ,16 ) print (a, b, c)
1.2 基本运算符 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 a = 5 ; b = 2 print (a**b) print (a // b) print (a / b) if a == 5 and b == 2 : print (b << 2 ) if a == 2 or b == 2 : print (a >> 1 ) arry=["hi" ,"im" ,"fine" ,"ok" ] print ("hi" in arry) print ('thank' not in arry) a = "1" b = 1 print (a is not b) b = "1" print (a is b)
1.3 基本语句 if 语句
1 2 3 4 5 6 7 8 9 10 a = 10 if a >= 12 : a = 1 elif a == 10 : a = 2 else : a = 3 print (a)
for, while 语句
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 sum = 0 a = range (1 ,10 ) b = range (1 ,10 ) for i in a: for j in b: if i >= j: sum = i*j print ("%d*%d=%d" %(i,j,sum ), end = "\t" ) print ("\n" ) pp=0 sum2=0 while pp<=10 : pp+=1 print () for o in range (1 ,11 ): sum2=pp+o if pp>=o: print ("%d+%d=%d" %(pp,o,sum2),end=' ' ) for l in range (1 ,11 ): print (l) else : print ("for normal end" )
2. 数据结构 2.1 list(列表) 有序的可变
序列 列表用于存储任意大小的数据集合, 可以是不同数据类型, 包括列表(嵌套)
关于初始化
1 2 3 4 5 6 7 8 9 10 11 12 list =list ("like u" ) list1=[1 ,23 ,4 ,"i" ,"forever" ,True ] list2=[x for x in range (1 ,11 ) if x>2 ] _list = list ((1 , 2 , 3 )) _list = list ({1 , 2 , 3 }) _list = list ({"a" : 1 , "b" : 2 }) _list = list (x for x in range (1 ,10 ) if (x > 5 ))
关于列表的访问
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 a = list (x for x in range (1 ,11 )) a.append(11 ) a.insert(1 , 'x' ) b = list (t for t in range (111 ,114 )) a.extend(b) a.remove('x' ) a.pop(len (a) - 1 ) del a[a.index(112 )]print (a.count(1 )) a.reverse() a.sort() a.sort(reverse=True ) print (sorted (a)) print (sorted (a, reverse=True ))a.clear() b = [["a" , 15 ], ["b" , 12 ], ["c" , 10 ]] def cmp (x ): return x[1 ] b.sort(key=cmp, reverse = True ) b.sort(key = lambda y: y[1 ]) c = ['apple' ,'dasdasdas' ,'h1' ] c.sort(key = len ) k=[1 ,2 ,5 ,3 ,2 ,4 ] k.sort(key=lambda x:x) k.sort(key=lambda x:-x)
2.2 tuple(元组) 有序的不可变
序列 元组用于存储任意大小的数据集合, 可以是不同数据类型, 包括元组(嵌套)
关于元组的初始化
1 2 3 4 5 6 7 8 9 a=(1 ) b=(1 ,) print (type (a)) print (type (b)) t1 = ("aa" , ) t1 = tuple ("aa" ) t1 = (x for x in range (1 , 10 )) t1 = tuple (x for x in range (1 ,10 ))
元组的访问和遍历
简单的for遍历, 可以访问, 但是无法修改和删除, 这也是和列表最大的区别 因此其常用的成员函数较少
.count(x)
.index(x)
.len()
ps
: 当元组内放置一个列表, 该子列表可以进行修改
1 2 m=(1 ,2 ,3 ,[4 ,5 ,6 ]) m[3 ][0 ]=5
2.3 序列 序列是基本的数据结构, 常见的序列有, 字符串, 元组, 列表
序列的通用操作
切片
1 2 3 4 5 6 7 8 9 10 11 str ="0123456789" print (str [0 :len (str )]) print (str [::])print (str [1 :5 ]) print (type (str [1 :3 ])) print (str [4 :1 :-1 ]) str = str [::-1 ] str = str [::-1 ][::-1 ]
连接和复制
1 2 3 4 a = tuple (x for x in range (1 ,3 )) b = tuple (x for x in range (4 ,6 )) c = a + b d = a * 3
成员检查
1 2 3 d=tuple (x for x in range (1 ,6 )) print (3 in d)print (11 not in d)
内置函数
1 2 3 4 d=tuple (x for x in range (1 ,7 )) print (len (d)) print (max (d)) print (min (d))
序列的相互转换
1 2 3 4 5 6 7 8 9 10 str ="hi" list_ = list (str ) tuple_ = tuple (str ) tuple_ = list (tuple_) list_ = tuple (list_) f = ['h' ,'i' ,"nine" ,"tse" ] e = '' print (e.join(f)) print (str (f))
关于str()函数
1 2 3 4 5 print (str (10 )) print (str (3.14 ) ) print (str ([1 , 2 , 3 ])) print (str (('a' , 'b' , 'c' ))) print (str ({'name' : 'John' , 'age' : 25 }))
2.4 dict(字典)
字典的创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a = {"key1" : 1 , "key2" : 2 } a["key1" ] = 2 b = [("red" ,1 ),("green" ,3 )] c = dict (b) c = dict (red = 1 , blue = 2 ) p = {x : x * 2 for x in range (1 , 6 )} l = [("red" , 1 ),("green" , 3 )] p = {x : j for x, j in l}
字典的更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 map = {"sewerperson" : {"music" : 700 , "sex" : "man" }, "nientail" : {"music" : 200 , "sex" : "women" }}map ["ninetse" ] = {"music" : 0 , "sex" : "manman" } print (map .keys()) print (map .values()) print (map .items()) for key in map : print (f"key is {key} , value is {map [key]} " ) map .pop("ninetse" ) del map ["nientail" ]
字典的复制和查询函数
1 2 3 4 5 6 7 8 9 10 11 12 13 a = {"k1" :1 ,"k2" :9 } print (a.get("k1" ,"404" )) print (a.get("k3" )) print (a.get("k3" ,"404" )) a = {"k1" :1 ,"k2" :9 } b = a c = a.copy() a["k1" ] = 2 print (a) print (b) print (c)
ps: 字典转为 list , tuple , set 都会只保留 key
2.5 set(集合) 可容纳不同类型 集合的特点是, 无序(元素位置和创建时不一), 不会出现重复元素
集合的创建
1 2 3 4 5 6 7 8 9 10 s1 = {'black' , "white" , "blue" , "blue" , 1 } s1 = set ("ninetse" ) m1 = ['1' , 2 , 3 , 4 ] m2 = (1 , 2 , 3 , "2" ) s1 = set (m1) s1 = set (m2) s1 = set () s1 = {i for i in range (1 ,11 )}
集合的访问: 由于set是无序的, 所以无法用下标访问, 但还是可以用for访问
集合的常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 a = {1 , 3 , 3 , 4 } a.add(9 ) a.remove(9 ) a.discard(5 ) a.pop() b = {2 , 9 , 5 , 3 } print (a.union(b)) print (a.difference(b)) print (b.difference(a)) print (9 in b) print (10 not in b) a.clear() del a
ps : 在集合中, 还重载了 各类运算符, 如 <=, ==, !=, &(交集), |(并集), -(差集), ^(差集)
3. 函数 在python中, 貌似没有成员函数, 而被称之为方法 函数内部创建的变量为局部变量 函数内部若想修改
全局变量, 需要在函数内先将要访问的变量前 + global
1 2 3 4 5 6 7 8 9 def oo (x, y ): print (x, y) print (oo(1 , 4 )) a = 100 def fun (): global a a+=100 fun()
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 def func (): return 1 ,2 x, y = func() print (type (func())) def func1 (): return 1 ,"hello" ,True a, b, c = func1() print (func1()) print (type (func1())) def func3 (x,y,z = 9 ): return x + y + z print (func3(x = 1 , y = 2 , z = 3 ))print (func3(x = 1 , y = 2 ))def funcc (*args ): print (f"args的类型是{type (args)} ,值是{args} " ) funcc(1 ,2 ,3 ,'小明' ) def funccc (**kwargs ): print (f"kwargs的类型是{type (kwargs)} ,值是{kwargs} " ) funccc(key1=1 ,key2=2 ) a=19 ;b=20 def compute (x,y ): return x+y def text (func ): result=func(a,b)+1 return result compute(a,b) text(compute) a=19 ;b=20 def text (computee ): result=computee(a,b) return result text(lambda x,y:x+y)
4. 文件操作
文件读取
1 2 3 4 5 6 7 8 9 10 11 12 def print_file_info (file_name ): f = None try : f = open (file_name, "r" , encoding = "utf-8" ) print (type (f)) except Exception as reason: print ("open file fail" ) else : print (f.read()) finally : if f: f.close()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 f = open ("C:/Users/sewerperson/Desktop/intro.cpp" ,"r" ,encoding = "UTF-8" ) print (f.read(2 )) print (f.readline(5 )) print (f.readline()) print (f.readlines(1 )) for i in f: print (i) print (f.read()) f.close() with open ("C:/Users/sewerperson/Desktop/intro.cpp" , "r" , encoding = "utf=8" ) as f: print (f.readlines()) print (f.read())
文件的写操作
1 2 3 4 5 6 7 f=open ("C:/Users/sewerperson/Desktop/intro.cpp" , "w" , encoding = "utf-8" ) f.write("add" ) f.flush() f.close() with open ("C:/Users/sewerperson/Desktop/intro.cpp" , "a" , encoding= "utf-8" ) as f: f.write("new" )
案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 count = 0 with open ("C:/Users/sewerperson/Desktop/intro.cpp" , "r" , encoding = "utf-8" ) as f: for line in f: w = line.split(" " ) print (w) for i in w: if i == "the" : count += 1 print (f"the出现的次数是{count} " )with open ("C:/Users/sewerperson/Desktop/intro.cpp" , "r" ,encoding = "UTF-8" ) as f: k = f.read() p = k.split(" " ) print (p.count("the" ))
1 2 3 4 5 with open ("C:/Users/sewerperson/Desktop/intro.cpp" ,"r" ,encoding="utf-8" ) as f: for line in f: line.strip() g = open ("xxx.txt" , "a" , encoding = "utf-8" ) g.write(f"{line} " )
1 2 3 4 f = open ("C:/Users/sewerperson/Desktop/intro.cpp" , "r" , encoding = "UTF-8" ) data=f.read() data=data.replace("replace me" ,'' ) data=data[:-2 ]
5. 异常 常见异常 :
assertionError assert (后面条件为假)
attributeError (尝试访问未知的对象属性)
index Error (索引超出序列范围)
keyError (字典中找到不存在的关键字)
osError (操作系统产生的异常)
nameError (尝试访问一个不存在的变量)
synataxError python (语法错误)
typeError (不同类型之间的无效操作)
zerodivisionError (除零错误)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 try : with open ("none.txt" , "r" , encoding = "utf-8" ) as f: print (f.read()) except OSError as reason: print ("error " , str (reason)) try : a=int (input ("请输入一个数" )) result=8 /a print (result) except ValueError as reason: print ("error " , str (result)) except Exception as reason: print ("annoymouse error %s" %str (reason)) except Exception as result: print ("some error %s" %result) except : print ("some error" ) else : print ("none error" ) finally : print ("dont care error" )
异常的传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def func1 (): print ("func1 start" ) 1 /0 print ("func1 end" ) def func2 (): print ("func2 start" ) func1() print ("func2 end" ) def main (): try : func2() except Exception as op: print (op) main()
6. 模块和包
外部模块的引入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import time time.sleep(10 ) from time import sleep sleep(3 ) from time import * sleep(3 ) from time import sleep as op op(3 ) import time as tt.sleep(3 )
自定义模块和包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 def add (x, y ): return x + y def surplus (x, y ): return x - y def add (x, y ): print (x - y) return x - y def surplus (x, y ): return x + y add(9 , 1 ) if __name__=='__main__' : add(1 ,5 ) __all__ = ['add' ] from pakage.app0 import *from pakage.app1 import *print (add(7 , 3 )) print (surplus(7 , 3 ))
引入第三方包
1 2 3 4 pip install 第三方包名 pip install https://pypi.tuna.tsinghua.edu.cn/simple/ 包名
json包
1 2 3 4 5 6 7 8 9 10 11 12 import jsondata = '{"a" : 1, "b" : 2, "c" : 3, "name" : "中文"}' obj = json.loads(data) jsondata = json.dumps(obj) readchinese = json.dumps(obj, ensure_ascii = False ) with open ("C:/Users/sewerperson/Desktop/intro.cpp" , "w" ) as file: json.dump(obj, file)
7. 类 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 class student : name = None sex = "man" age = 1 __privatemsg = 1980 def __privatefunc (self ): print ("private func" ) def callprivate (self ): self.__privatefunc() print (self.__privatemsg) def classfunc (self ): print (f"show my name {self.name} " ) def __init__ (self, name, sex, age ): self.name = name self.sex = sex self.age = age def __str__ (self ): return (f"{self.name} , {self.sex} " ) def __it__ (self, other ): return self.age < other.age def __le__ (self, other ): return self.age <= other.age def __gt__ (self, other ): return self.age > other.age def __ge__ (self, other ): return self.age >= other.age def __eq__ (self, other ): return self.age == other.age student2 = student("tail" , "manb" , 18 ) student3 = student("tail" , "woman" , 17 ) print (student2.__it__(student3)) print (student2 < student3) print (student2 <= student3) print (student2 > student3) print (student2 >= student3) print (student2 == student3) print (str (student2))
类的继承
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 class phone : name = "honor" def ptname (self ): print ("im honor" ) class phone2022 : name = "huawei" def ptname (self ): print ("im huawei" ) class phone2024 (phone, phone2022): age = 12 def ptage (self ): print ("12 year" ) def ptname (self ): print ("im xiaomi" ) super ().ptname() phone2022.ptname(self) a = phone2024() a.ptname()
多态的简单实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class animal : def speak (self ): pass class dog : def speak (self ): print ("bark" ) class cat : def speak (self ): print ("mi" ) def voice (a : animal ): a.speak() dog = dog() cat = cat() voice(dog) voice(cat)
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 class airconditioner : def make_cool (self ): pass def make_hot (self ): pass def swing (self ): print ("??? me" ) pass class geli (airconditioner ): def make_cool (self ): print ("geli make cool" ) def make_hot (self ): print ("geli make warm" ) class meidi (airconditioner ): def make_cool (self ): print ("meidi make cool" ) def make_hot (self ): print ("meidi make warm" ) def swing (self ): print ("meidi wave" ) def makecool (object : airconditioner ): object .make_cool() def makewarm (object : airconditioner ): object .make_hot() def swing (object : airconditioner ): object .swing() airmeidi = meidi() airgeli = geli() makecool(airgeli) makecool(airmeidi) makewarm(airgeli) makewarm(airmeidi) swing(airgeli) swing(airmeidi)
8. 类型注解 类型注解(Type Annotations)为变量、参数、函数返回值等提供了类型信息。 这在代码的可读性, 代码分析和开发工具的支持方面有帮助 但是在运行时, 类型注解不会强制执行
, 也不会引发错误
1 2 3 4 5 6 7 8 9 10 def func (a:int , b:str ) -> int : print (a,b) return a print (func(3 , "hello" ))print (func("hello" , 9 ))
Union 的使用
1 2 3 4 5 6 7 8 9 10 from typing import Union mylist : list [Union [int , str ]] = [1 , "s" , "h" , 4 , 5 ] mydict : dict [Union [int , str ], Union [int , str ]] = {1 : 2 , 1 : "hi" , "l" : 1 , "i" : "b" } def useunion (data : Union [int , str ] ) -> Union [int , str ]: print (data) return 1
9. 进阶功能 9.1 闭包
不定义全局变量, 让函数持续访问或修改一个外部的变量
nonlocal
是一个关键字, 用于在嵌套函数中声明一个变量为非局部变量 默认情况下, 内部函数只能读取外部函数的变量, 而不能修改它们 在内部函数中使用nonlocal
关键字声明一个变量时 Python会沿着作用域链向上查找, 找到最近的外部函数中
具有相同名的变量, 并将其标记为非局部变量nonlocal
关键字只能在嵌套函数中使用,而不能在全局作用域或单独的函数中使用 无需通过定义全局变量,就可以通过函数实现持续访问,操作某个值 闭包使用的变量在函数内,很难被错误的误改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def account_mount (total = 0 ): def atm (money, choose = True ): nonlocal total if choose: total += money print (f"put money: +{money} , remain:{total} " ) else : total -= money print (f"get money: -{money} , remain:{total} " ) return atm atm = account_mount() atm(100 ) atm(100 ) atm(100 , False )
缺点 : 由于一直持续的引用外部函数的变量,会占用内存
9.2 装饰器
不修改原函数内容情况下为函数添加新功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import timedef outer (sleep ): def inner (): print ("now sleep" ) sleep() print ("now get up" ) return inner @outer def sleep (): print ("sleeping" ) time.sleep(2 ) sleep() sheep = outer(sleep) sheep()
9.3 多线程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import threading,timedef sing (song ): while True : print (f"sing {song} " ) time.sleep(1 ) def dance (music ): while True : print (f"dance {music} " ) time.sleep(1 ) sing = threading.Thread(target = sing, args = ("kk" , )) dance = threading.Thread(target = dance, kwargs = {"music" : "msg" }) sing.start() dance.start()
target
: 指定线程要执行的函数或可调用对象 默认是 Noneargs
: 指定传递给 target 的位置参数。默认是 () 元组kwargs
: 指定传递给 target 的关键字参数 默认是 {} 字典daemon
: 指定线程是否是守护线程, 守护线程在主线程结束后会自动终止, 默认是 None, 表示继承主线程的守护状态name
: 指定线程的名字, 默认会生成一个唯一的线程名, 如 Thread-1、Thread-2
9.4 网络编程 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 import socketsocket_severe = socket.socket() socket_severe.bind(("localhost" , 8888 )) socket_severe.listen(1 ) client_socket, client_address = socket_severe.accept() print (f"client address is {client_address} " )while True : client_msg = client_socket.recv(1024 ).decode("UTF-8" ) print (f"client send : {client_msg} " ) severe_sentmsg = input ("reply to client : " ) client_socket.send(severe_sentmsg.encode("UTF-8" )) if severe_sentmsg == 'exit' : break client_socket.close() socket_severe.close()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import socketclient_socket=socket.socket() client_socket.connect(("localhost" ,8888 )) while True : sent_data=input ("send server is : " ) if sent_data == "exit" : break client_socket.send(sent_data.encode("UTF-8" )) recv_data = client_socket.recv(1024 ) print (f"server reply : {recv_data.decode('UTF-8' )} " ) client_socket.close()
9.5 正则表达式
正则表达式, 又称规则表达式( Regular Expression), 是使用单个字符串来描述、匹配某个句法规则的字符串 常被用来检索、替换那些符合其个模式(规则)的文本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import re str = "python ppypyyp python" result = re.match ("python" ,str ) print (result) print (result.span()) print (result.group()) str = "ppppythonnn pp pythonnn" result = re.search("python" ,str ) print (result) print (result.span()) print (result.group()) result = re.findall("python" ,str ) print (result)
元字符匹配
字符
描述
.
匹配除换行符之外的任何单个字符
[]
匹配[]中列举的字符
\d
匹配任何数字(等同于[0-9]
)
\D
匹配任何非数字
\w
匹配任何字母数字或下划线字符
\W
匹配任何非字母数字或下划线字符
\s
匹配任何空白字符(空格、制表、换行)
\S
匹配任何非空白字符
数量匹配
字符
描述
*
匹配0次或多次
+
匹配1次或多次
?
匹配0次或1次
{n}
精确匹配n
次
{n,}
匹配至少n
次
{n,m}
匹配至少n
次,但不超过m
次
边界匹配
字符
描述
^
匹配字符串的开始
$
匹配字符串的结束
\b
匹配单词边界
\B
匹配非单词边界
\A
匹配整个字符串的开始
\Z
匹配整个字符串的结束
分组匹配
字符
描述
()
用于创建分组
|
匹配左右任意一个表达式
案例
1 2 3 4 5 6 7 8 只能数字和字母, 长度6-10 ^[0-9a-zA-Z]{6, 10}$ 纯数字, 长度5-11, 第一位不为0 ^[1-9][0-9]{4, 10}$ 只允许qq,163,gmail三种邮箱地址 ^[\w]+(\.[\w-]+)*@(qq|163|gmail)(\.[\w-]+)+$
以上