安装python解释器 下一步 在下一步 完成后 win+r 输入cmd python
编写第python一个程序
print("hello,world!")
python模块的安装与使用
安装
pip install 模块名
列出所有模块
pip list
模块的使用
import 模块名from 模块名import 对象名
python 序列
列表
// 创建列表student = ['number','id','age']print(student)# ['number', 'id', 'age']// list() 函数将元组 字符串 字典等可迭代对象强转为列表num = list((1,2,3,4,5))print(num)# [1, 2, 3, 4, 5]// 删除列表student = ['number','id','age']del student[0]print(student)# ['id', 'age']// 添加元素student = ['number','id','age']student.append('class')print(student)# ['number', 'id', 'age', 'class']// 列表中添加列表student = ['number','id','age']lit = [18,20,20]student.extend(lit)print(student)# ['number', 'id', 'age', 18, 20, 20]// 在指定位置添加元素li1 = [1,2,3,4]li2 = '2.0'li1.insert(2,li2) // 在元素2 后面添加字符串 2.0print(li1)# [1, 2, '2.0', 3, 4]// 删除指定的元素li1 = [1,2,3,4]li1.remove(1)print(li1)# [2, 3, 4]//返回指定元素在列表出现的次数li1 = [1,2,3,4,1,1,1]ret = li1.count(1)print(ret)# 4 1出现4次// 将列表中的元素逆序li1 = [1,2,3,4]li1.reverse()print(li1)# [4, 3, 2, 1]// 对元素进行排序// key指定排序依据,reverse决定升序(False)还是降序(True)li1 = [2,5,7,3,1,9]# 升序li1.sort(key=str,reverse=False)print(li1) # [1, 2, 3, 5, 7, 9]# 降序li1.sort(key=str,reverse=True)print(li1) # [9, 7, 5, 3, 2, 1]
元组
tu = (1,2,3)print(tu)# (1, 2, 3)
字典
// 基本语法dic = {'v1':'k1','v2':'k2'}print(dic)# {'v1': 'k1', 'v2': 'k2'}// 通过dict创建字典dic = dict(name='阿杰',age=18)print(dic)# {'name': '阿杰', 'age': 18}// 修改字典中的元素dic = dict(name='阿杰',age=18)dic['age']=20print(dic)# {'name': '阿杰', 'age': 20}// 添加新元素dic = dict(name='阿杰',age=18)dic['sex'] = 'man'print(dic)# {'name': '阿杰', 'age': 18, 'sex': 'man'}// 返回字典中所有的元素dic = dict(name='阿杰',age=18)dic.items()print(dic)//删除字典中的元素dic = dict(name='阿杰',age=18)del dic['age']print(dic)# {'name': '阿杰'}
总结:
列表外面是中括号
元组外面是花括号
字典外面是大括号
if 判断
age = 40if age > 30: print("回家养老吧")# 回家养老吧num = 80if num >=90: print("优秀")elif num >= 80: print("良好")else: print("你太优秀了,学校不是你呆的地方!")
循环结构
for循环# 打印1+2+3+...+100 的和sum = 0for i in range(1,101): sum = sum + iprint(sum)while循环sum = 0i = 1while i < 101: sum = sum + i i += 1print(sum)
文件处理
# ### 文件操作"""fp = open(文件名,模式,字符编码集)fp 文件的io对象(文件句柄)i => input 输入o => output 输出对象可以实现操作:对象.属性对象.方法()"""# 一.文件的写入操作# (1) 打开文件fp = open("ceshi1.txt",mode="w",encoding="utf-8") #打开冰箱门print(fp)# (2) 写入内容fp.write("我就是想赛个大象进去") # 把大象塞到冰箱里头# (3) 关闭文件fp.close() #关上冰箱门# 二.文件的读取操作# (1) 打开文件fp = open("ceshi1.txt",mode="r",encoding="utf-8")# (2) 读取内容res = fp.read()print(res)# (3) 关闭文件fp.close()# 三.二进制字节流"""文件可以存放两种内容:(1)字符串(2)二进制字节流二进制字节流: 数据传输时的一种格式表达方式: (1)b开头 比如b"123" 对字符有要求:ascii编码 (2)如果表达中文,使用encode和decode# 将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式) #encode() 编码 将字符串转化为字节流(Bytes流) #decode() 解码 将Bytes流转化为字符串"""strvar = b"abc"# strvar = b"中文" errorprint(strvar,type(strvar))# 把中文变成二进制的字节流strvar = "我爱你"res = strvar.encode() # b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0'print(res)strvar = b"\xe7\x88\xb1"res = strvar.decode()print(res)# 四.存储二进制字节流 (如果存入的是字节流,不需要指定encoding)# 写入二进制字节流fp = open("ceshi2.txt",mode="wb")strvar = b"\xe7\x88\xb1"fp.write(strvar)fp.close()# 读取二进制字节流fp = open("ceshi2.txt",mode="rb")res = fp.read()print(res) # b'\xe7\x88\xb1'res2 = res.decode()print(res2)fp.close()# 五.复制文件"""图片 音频 视频 都是文件,里面的内容都是二进制字节流"""# 1.读取图片当中所有内容(二进制字节流)fp = open("集合.png",mode="rb")bytes_str = fp.read()fp.close()print(bytes_str)# 2.把读出来的字节流写入到另外一个文件中fp = open("jihe2.jpg",mode="wb")fp.write(bytes_str)fp.close()# ### 一 文件扩展模式# (utf-8编码格式下 默认一个中文三个字节 一个英文或符号 占用一个字节)#read() 功能: 读取字符的个数(里面的参数代表字符个数)#seek() 功能: 调整指针的位置(里面的参数代表字节个数)#tell() 功能: 当前光标左侧所有的字节数(返回字节数)"""seek(0) 把光标移动到文件的开头seek(0,2) 把光标移动到文件的末尾"""# r+ 先读后写"""fp = open("ceshi2.txt",mode="r+",encoding="utf-8")# 先读res = fp.read()# 后写fp.write("123")# 在读fp.seek(0)res = fp.read()print(res,"<=====>")fp.close()""""""# r+ 先写后读fp = open("ceshi2.txt",mode="r+",encoding="utf-8")# 先写fp.seek(0,2) # 把光标移动到最后fp.write("lmn")# 在读fp.seek(0) # 把光标移动到文件的开头res = fp.read()fp.close()print(res)""""""# w+ 可读可写fp = open("ceshi4.txt",mode="w+",encoding="utf-8")# 写入fp.write("你好我的baby")# 读取fp.seek(0)res = fp.read()print(res)fp.close()""""""# a+ 可读可写 (在写入内容时,会强制把光标移动到最后)# a模式和w模式,默认都能自动创建文件fp = open("ceshi5.txt",mode="a+",encoding="utf-8")# 写入fp.write("今天天气不错")# 读取fp.seek(0)res = fp.read()print(res)fp.close()fp = open("ceshi6.txt",mode="a+",encoding="utf-8")# 移动光标 (无论如何移动,写入内容都是以追加的形式呈现)fp.seek(3)fp.write("456")fp.close()"""# ### 二.read , seek , tell 三个函数使用fp = open("ceshi6.txt",mode="r+",encoding="utf-8")# read 里面的参数,单位是字符个数res = fp.read(3) # 读取3个字符# seek 移动光标fp.seek(7) # fp.seek(5) 光标卡在中所代表的三个字节中的中间位置res = fp.read()print(res)# tell 从当前光标往左读取,累计所有的字节数res = fp.tell()print(res)# ### 三.注意点 (中文混合的情况)"""# abcd\xe6\x88\x91\xe7\x88\xb1""""""fp = open("ceshi6.txt",mode="r+",encoding="utf-8")fp.seek(5)res = fp.read()print(res)fp.close()"""# ### 四.with 语法 (可以省略掉close操作)"""with open() as fp:code .. """# 读取图片当中所有内容 (二进制字节流)"""with open("集合.png",mode="rb") as fp:bytes_str = fp.read()with open("jihe3.gif",mode="wb") as fp:fp.write(bytes_str)"""# 在升级,用三行代码实现with open("集合.png",mode="rb") as fp1,open("jihe4.gif",mode="wb") as fp2:bytes_str = fp1.read()fp2.write(bytes_str)
异常处理
try ... except ... 属于成绩1-100 超出则报错 socre = input("请输入成绩:")try: socre = int(socre) if (0 <= socre <= 100 ): print("你的成绩为:", socre) else: print("输入有误,请重试!")except Exception as a: print("nononono")# 请输入成绩:90# 你的成绩为: 90# 请输入成绩:190# 输入有误,请重试!// try ... except ... else socre = input("请输入成绩:")try: socre = int(socre)except Exception as a: print("nononono")else: if (0 <= socre <= 100 ): print("你的成绩为:", socre) else: print("输入有误,请重试!") // try except finallya = int(input('a:' ))b = int(input('b:' ))try: div = a/b print(div)except Exception as e: print("======")finally: print("over")
socket 编程
server:import socket# 明确配置变量ip_port = ('127.0.0.1', 8080)back_log = 5buffer_size = 1024# 创建一个TCP套接字ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 套接字类型AF_INET, socket.SOCK_STREAM tcp协议,基于流式的协议ser.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 对socket的配置重用ip和端口号# 绑定端口号ser.bind(ip_port) # 写哪个ip就要运行在哪台机器上# 设置半连接池ser.listen(back_log) # 最多可以连接多少个客户端while 1: # 阻塞等待,创建连接 con, address = ser.accept() # 在这个位置进行等待,监听端口号 while 1: try: # 接受套接字的大小,怎么发就怎么收 msg = con.recv(buffer_size) if msg.decode('utf-8') == '1': # 断开连接 con.close() print('服务器收到消息', msg.decode('utf-8')) except Exception as e: break# 关闭服务器ser.close()clinet:import socketp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)p.connect(('127.0.0.1', 8080))while 1: msg = input('please input: ') # 防止输入空消息 if not msg: continue p.send(msg.encode('utf-8')) # 收发消息一定要二进制,记得编码 if msg == '1': breakp.close()