python基础

1、python的数据类型:数字:int、float、complex、bool;字符串(不支持修改)、列表、元组(不可修改的list,如果元组中嵌套了list,嵌套的list可以修改)、集合、字典(map)

2、字面量:常数

3、变量无类型,但是变量存储的字符串等是有类型的

4、函数例子

python 复制代码
money = 5000000
name = input("请输入姓名:")
def query(show_header):
    if show_header:
        print("------------查询余额-----------")
    print(f"你好{name},您的余额为{money}元")

def save(num):
    global money
    money += num
    print("------------存款-----------")
    print(f"你好{name},您存款{num}元成功")
    query(False)

def get(num):
    global money
    money -= num
    print("------------取款-----------")
    print(f"你好{name},您取款{num}元成功")
    query(False)

def main():
    print("------------主菜单-----------")
    print(f"{name}您好,有如下服务")
    print('查询余额\t输入1')
    print("存款\t\t输入2")
    print("取款\t\t输入3")
    print("退出\t\t输入4")
    return input("请输入选择结果:")

while True:
    key = main()
    if key == "1":
        query(True)
        continue
    elif key == "2":
        num = int(input("请输入存款金额:"))
        save(num)
        continue
    elif key == "3":
        num = int(input("请输入取款金额:"))
        get(num)
        continue
    else:
        print("程序退出")
        break

5、文件操作

python 复制代码
#克隆第一个文件中带有py的内容到第二个文件中,使用追加方式
with open("D:/test/test1.txt","r",encoding="utf-8") as f ,open("D:/test/test4.txt","a",encoding="utf-8") as ff:
    for line in f:
        if line.__contains__("py"):
            ff.write(line)
with open("D:/test/test4.txt","r",encoding="utf-8") as fff:
    print(fff.read())
def pring_file_info(path):
    try:
        with open(path,"r",encoding="utf-8") as f:
            for line in f:
                print(line)
    except Exception as e:
        print(e)

def append_to_file(path,data):
    try:
        with open(path,"a",encoding="utf-8") as f:
            f.write(data)
    except Exception as e:
        print(e)

if __name__ == "__main__":
    pring_file_info("D:/test/te.txt")
    append_to_file("D:/test/test4.txt","hello world")
    pring_file_info("D:/test/test4.txt") 

6、异常操作

python 复制代码
#捕获所有异常
try:
    open("D:/t.txt","r",encoding="utf-8")
except:
    print("出现异常,文件不存在")
#捕获指定的多个异常
try:
    print(1/0)
except (NameError,ZeroDivisionError) as e:
    print(e)
#捕获指定的所有异常
try:
    print(1/0)
except Exception as e:
    print(e)

try:
    print("uuuuuu")
except Exception as e:
    print(e)
else:
    print("无异常")
finally:
    print("永远执行")

try:
    print(1/0)
except Exception as e:
    print(e)
else:
    print("无异常")
finally:
    print("永远执行")

7、异常的传递:从fun1传递到fun2,传递到main

python 复制代码
def fun1():
    print("start...")
    print(1/0)
    print("over...")

def fun2():
    print("start...")
    fun1()
    print("over...")

def main():
    try:
        fun2()
    except Exception as e:
        print(e)

main()

8、抽象类

python 复制代码
class AC:
    def cool(self):
        pass

    def hot(self):
        pass

    def swing(self):
        pass

class Minea_AC:
    def cool(self):
        print("Minea_AC冷风")

    def hot(self):
        print("Minea_AC热风")

    def swing(self):
        print("Minea_AC摇晃")

class GREE_AC:
    def cool(self):
        print("GREE_AC冷风")

    def hot(self):
        print("GREE_AC热风")

    def swing(self):
        print("GREE_AC摇晃")

def work(ac:AC):
    ac.hot()

mdea = Minea_AC()
gree = GREE_AC()

work(mdea)
work(gree)

9、pymysql

python 复制代码
from pymysql import Connection

conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="password",
    autocommit=True
)

cursor = conn.cursor()
conn.select_db("db7")
#cursor.execute("create table test_py(id int,city varchar(20));")
cursor.execute("insert into happy values(11,'www',19,1)")
#conn.commit()
cursor.execute("select * from happy")
res = cursor.fetchall()
for r in res:
    print(r)
print(conn.get_server_info())
conn.close()

10、闭包

python 复制代码
def account_creat(init_account):
    def ATM(num,disposit=True):
        nonlocal init_account
        if disposit:
            init_account += num
            print(f"存钱{num}成功,账户余额{init_account}")
        else:
            init_account -= num
            print(f"取钱{num}成功,账户余额{init_account}")
    return ATM
atm = account_creat(100)
atm(100,True)

11、装饰器

python 复制代码
import random
import time
def outer(fun):
    def inner():
        print("开始")
        fun()
        print("结束")
    return inner
#将sleep作为参数传入outer中,outer作为装饰器
@outer
def sleep():
    print("睡眠中")
    time.sleep(random.randint(1,5))

sleep()

12、多线程

python 复制代码
import threading
import time
def sing(msg):
    while True:
        print("singing...",msg)
        time.sleep(1)
def dance(msg):
    while True:
        print("dancing...",msg)
        time.sleep(1)
if __name__ == '__main__':
    thread1 = threading.Thread(target=sing,args=("hahahaha",))
    thread2 = threading.Thread(target=dance,kwargs={"msg":"lllll"})
    thread1.start()
    thread2.start()

13、socket通信

1)服务端

python 复制代码
import socket

socket_server = socket.socket()
socket_server.bind(("localhost",8888))
#表示允许连接的数量
socket_server.listen(1)
#等待客户端连接,是阻塞的方法,如果没有客户端连接,就一直阻塞到这里
conn,address = socket_server.accept()
print(f"接收到了客户端连接,客户端的地址是{address}")
while True:
    #recv接收的数字是缓冲区大小,返回的data是字节数组
    data: str = conn.recv(1024).decode("UTF-8")
    print(f"客户端发来的消息是:{data}")
    msg = input("请输入你要和客户端回复的消息:")
    if msg == "exit":
        break
    #发送消息
    conn.send(msg.encode("UTF-8"))

#关闭连接
conn.close()
socket_server.close()

2)客户端

python 复制代码
import socket

#创建客户端对象
socket_client = socket.socket()
#连接到服务端
socket_client.connect(("localhost",8888))

while True:
    msg = input("请输入发给服务端的消息:")
    if msg == "exit":
        break
    #发送消息
    socket_client.send(msg.encode("utf-8"))
    #接收服务端消息
    data = socket_client.recv(1024)
    print(f"服务端回复的消息是:{data.decode("utf-8")}")

#关闭连接
socket_client.close()

14、正则表达式

python 复制代码
import re

s = "python aaa bbb ccc pythonaa python"
res = re.match("python",s)
print(res)
print(res.group())
print(res.span())

res = re.search("python",s)
print(res)

res = re.findall("python",s)
print(res)
相关推荐
Hx_Ma161 小时前
测试题(五)
java·开发语言·后端
froginwe111 小时前
SQL 主机:深入解析数据库的核心
开发语言
yy.y--1 小时前
Java文件读取实战:用FileInputStream显示源码
java·开发语言
m0_531237171 小时前
C语言-函数练习
c语言·开发语言
我是大猴子1 小时前
异常的处理
java·开发语言
~央千澈~1 小时前
抖音弹幕游戏开发之第16集:异常处理与稳定性·优雅草云桧·卓伊凡
开发语言·php
清水白石0081 小时前
解锁 Python 性能潜能:从基础精要到 `__getattr__` 模块级懒加载的进阶实战
服务器·开发语言·python
清水白石0081 小时前
缓存的艺术:Python 高性能编程中的策略选择与全景实战
开发语言·数据库·python
AI Echoes1 小时前
对接自定义向量数据库的配置与使用
数据库·人工智能·python·langchain·prompt·agent