python笔记

目录

python学习

idge

miniconda的安装

下载地址

基础知识

常量与变量

常量:一个不变的值,例如数字。
变量:由下面可知,num的值由100,变成了101,num重新赋值了。如同杯子装的水,到了又重新接的水。容器。

num=100
num=101

数据类型

查找数据类型的方法是type()

int_type=1#整数类型
float_type=1.2#浮点数类型
str_type='中国'#字符串类型
list_type=['1',2]#列表类型
tuple_type=(1,)#元组类型
dict_type={'1':1}#字典类型
set_type={1,'2'}#集合类型
bool_type=True#布尔类型
print(type(int_type),type(float_type),type(str_type),type(list_type),type(tuple_type),type(dict_type),type(set_type),type(bool_type))

image

查看关键字

import keyword
print(keyword.kwlist)

占位符

print('%s:字符串占位,%d:数字占位,%f:浮点数占位,%.2f:保留2位小数,支持四舍五入'%('小明',1,1.222,1.225))

image

输入方法

user_name='小明'
password=123
input('请输入用户名:')
input('请输入密码:')
if user_name=='小明'and int(password)==123:
    print('登录成功')
else:
    print('登录失败')

image

运算符

优先顺序
**>* / >%>//>+ -
#使用赋值运算赋值多个值
a,b,c=1,2,3
print(a,b,c)
#复合赋值运算符
a=1
a+=1#a=a+1
print(a)

image

判断语句

True,False的使用

is_True=True
is_False=False
if is_True:
   print('是真的')
else:
    print('不是真的')

image

比较运算符

ascii表查询

print(1>2)
print(1>=2)
print('a'>='b')#比较ascii

image

逻辑运算

print(1 and 2,1 or 2)
print(1>2 and 3,1>2 or 3)
print(1<2 and 3,1<2 or 3)
print(1<2 and 3>0,1<2 or 3>0)
print(1<2 and 3<2,1<2 or 3<2)
print(not False)

image

if elif else

age=eval(input('请输入你的年龄:'))
if age>=0 and age<18:
    print('未成年')
elif age==18:
    print('可以上网了')
elif age>18 and age<24:
    print('快毕业了')
elif age>=24 and age<100:
    print('可以参加工作了')
else:
    print('你输入的不符合')

image

if嵌套

ticket=True
restricted_knife=9
if ticket:
    if restricted_knife<9:
        print('检查合格,可以进站')
    else:
        print('检查不合格,不可以进站')
else:
    print('没有票,请买票')

image

while

#计算1-100的累积和(包含1和100)
# index=1
# sum=0
# while index<=100:
#     sum+=index
#     index+=1
# print(sum)
#计算1-100这间偶数的累积和(包含1和100)
# index=1
# even_number_sum=0
# while index<=100:
#     if index%2==0:
#         even_number_sum+=index
#     index+=1
# print(even_number_sum)
#实现计算1-100之间能补3整除且能够7整除的所有数之和
# index=1
# sum=0
# while index<100:
#     if index%3==0 and index%7==0:
#        sum+=index
#     index+=1
# print(sum)
#1--->1
# index=1
# while index<=5:
#     print('%d--->%d'%(index,index*index))
#     index+=1
#while嵌套练习
# index=1
# while index<=5:
#     print('*'*index)
#     index+=1
# i=1
# while i<=5:
#     j=1
#     while j<=i:
#         print('*',end='')
#         j+=1
#     print()
#     i+=1
#x*y=z
# i=1
# while i<=5:
#     j=1
#     while j<=i:
#         print('x*y=z',end=' ')
#         j+=1
#     print()
#     i+=1
# i=1
# while i<=9:
#     j=1
#     while j<=i:
#         print('%dx%d=%d'%(j,i,i*j),end=' ')
#         j+=1
#     print()
#     i+=1

for

for i in range(3,0,-1):
    password=input(f'请输入你的密码:(你还剩余{i}次机会):')
    if password=='admin':
        print('密码输入正确。。。')
        break
else:
    print('密码输入错误,次数已用完')

image

容器

字符串

find方法查找
"""find方法"""
my_str='akjlkjflkdj'
print(my_str.find('k'))#从左到右查找到第一个,并返回下标
print(my_str.rfind('k'))#从右到左查找到第一个,并返回下标

image

count方法统计
"""count方法"""
my_str='akjlkjflkdj'
print(my_str.count('k'))#统计字符的个数

image

replace替换
"""replace方法"""
my_str='www.baidu.com'
print(my_str.replace('w','W',2))#2替换次数

image

split分割

"""split方法"""
my_str='www.baidu.com'
print(my_str.split('.',1))#1分割次数

image

startswith endswith判断开头,结尾
"""startswith和endswith方法"""
my_str='www.baidu.com'
print(my_str.startswith('w'))#判断开头
print(my_str.endswith('com'))#判断结尾

image

lower upper小写,大写
"""lower和upper方法"""
my_str='WWW.baidu.com'
print(my_str.lower())#所有字符转为小写
print(my_str.upper())#所有字符转为大写

image

strip 删除两边空格
"""strip方法"""
my_str='   WWW.baidu.com   '
print(my_str)
print(my_str.strip())#删除字符串两边的空格

image

partition拆分为三部分
"""partition方法"""
my_str='www.baidu.com'
print(my_str.partition('.baidu.'))#拆分为三部分,元组形式

image

splitlines行分割
"""splitlines方法"""
my_str="""welcome to www.baidu.com
thank you
good
"""
print(my_str.splitlines())#拆分为三部分,元组形式

image

isalpha是否全为字母
"""isalpha方法"""
my_str='akjlkj'
print(my_str.isalpha())#判断是否全为字母组成的

image

isdigit是否全为数字
"""isdigit方法"""
my_str='123456'
print(my_str.isdigit())#判断是否全为数字组成的

image

isalnum是否以字母和数字组成
"""isalnum方法"""
my_str='123456jk'
print(my_str.isalnum())#判断是否为数字和字母组成的

image

join字符串的拼接
"""join方法"""
str_list=['a','k','klj']
print(''.join(str_list))#字符串拼接

image

列表

添加
stu_info=['吕布','刘备']
#在未尾添加一个值
stu_info.append('曹操')
print(stu_info)
#在未尾添加多个值
stu_info.extend(['张飞','关羽'])
print(stu_info)
#指定位置添加
stu_info.insert(1,'孙权')
print(stu_info)

image

修改
stu_info=['吕布', '孙权', '刘备', '曹操', '张飞', '关羽']
stu_info[0]='修改'
print(stu_info)

image

统计
stu_info=['吕布', '孙权', '刘备', '曹操', '张飞', '关羽','吕布']
print(stu_info.count('吕布'))#统计个数
print(stu_info.count('k'))#没有返回0

image

删除
stu_info=['吕布', '孙权', '刘备', '曹操', '张飞', '关羽','吕布']
del stu_info[1] #根据索引删除
print(stu_info)
str_name=stu_info.pop()#不填删除最后一个
print(str_name)
print(stu_info)
str_name2=stu_info.pop(0)
print(str_name2)
print(stu_info)
stu_info.remove('张飞')#根据值删除
print(stu_info)

image

列表嵌套
import random
"""
需求:定义一个学校,学校中有三间办公室,完成八名老师随机分配到三间办公室中
"""
#定义一个学校,并且学校包含了3个办公室
offices=[[],[],[]]
#定义老师
names=['A','B','C','D','E','F','G','H']
for name in names:
    random_num=random.randint(0,2)#随机生成办公室
    offices[random_num].append(name)
#定义办公室编号
office_index=1
for office_name in offices:
    print(f'办公室编号为:{office_index},人数为:{len(office_name)}')
    office_index+=1
    for teacher_name in office_name:
        print(teacher_name,end=' ')
    print()
    print('-'*30)

image

集合

add添加
"""add方法"""
int_set={1,2,3}
int_set.add(4)
print(int_set)

image

clear清空
"""clear方法"""
int_set={1,2,3}
int_set.clear()
print(int_set)

image

copy复制
"""copy方法"""
int_set={1,2,3}
int_set2=int_set.copy()
print(id(int_set),id(int_set2))#地址不一样

image

pop随机
"""pop方法"""
int_set={1,2,3}
int_set2=int_set.pop()#随机弹出一个元素,并删除
print(int_set)
print(int_set2)

image

"""remove方法"""
int_set={1,2,3}
int_set.remove(3)#指定元素并删除
print(int_set)

image

"""discard方法"""
int_set={1,2,3}
int_set.discard(2)#删除的值在集合内就删除,不在也不报错
print(int_set)
交集,并集,差集,对称差集
#交集
int_list1={1,2,3}
int_list2={1,2,4,5}
print(int_list1&int_list2)
#并集
print(int_list1 | int_list2)
#差集
print(int_list1.difference(int_list2))
print(int_list1 -int_list2)
#对称差集运算
print(int_list1 ^ int_list2)

image

字典

get获取
#数据查询方式-get
stu_info={
    'name':'吕布',
    'gender':'男',
    'age':23
}
# print(stu_info['QQ'])#没有找到会报错  KeyError: 'QQ'
print(stu_info.get('QQ'))#没有找到会返回Node
print(stu_info.get('QQ','找不到你要的键'))#第二个参数自形修改

image

修改
#数据修改
stu_info={
    'name':'吕布',
    'gender':'男',
    'age':23
}
stu_info['name']='刘备'
print(stu_info)

image

添加
#添加数据
stu_info={
    'name':'吕布',
    'gender':'男',
    'age':23
}
stu_info['address']='重庆'
print(stu_info)

image

函数

打印函数内部注释
def send_message(message):
    """

    :param message: 当前参数需要接收用户编辑的信息
    :return:
    """
    pass
print(send_message.__doc__)

image

函数调用
def test(num1,num2):#形参,调用函数储存数据的变量
    print('第一个数%d'%num1)
    print('第二个数%d'%num2)
    print('它们的和为%d'%(num1+num2))
test(1,2)#实参

image

函数返回值
def test(num1,num2):#形参,调用函数储存数据的变量
    print('第一个数%d'%num1)
    print('第二个数%d'%num2)
    return num1+num2
result=test(1,2)#实参
print(result)

image

四种函数类型
"""无参数,无返回值"""
def test():
    print('你好呀')
test()
"""有参数,无返回值"""
def test1(num):
    print(num)
test1(1)
"""无参数,有返回值"""
def test2():
    return '你好'
result=test2()
print(result)
"""有参数,有返回值"""
def test3(num):
    return num
result=test3(2)
print(result)

image

函数拆包的使用
def test(num,num2):
    return num,num2
num,num2=test(1,2)
print(num,num2)

image

匿名函数的使用
result=lambda x,y:x+y
print(result(1,2))

image

函数递归
def mult_nums(n):
    if n>1:
        print(n)
        return n*mult_nums(n-1)
    else:
        return 1
result=mult_nums(3)
print(result)

image

类的创建
class Hero:
    """info是一个实例方法,类对象可以调用实例方法,实例方法的第一个参数一下是self"""
    def info(self):
        print(self)
h1=Hero()#创建一个对象
h1.info()#对象调用实例方法
print(h1)#打印对象,则默认打印对象在内存的地址
print(id(h1))#id(h1)则是内存地址的十进制形式表式

image

属性的使用
class Hero:
    def set_info(self):
        self.name='吕布'
        self.age=22
        self.address='长沙'
    def print_info(self):
        print(self.qq,self.email)
#创建实例对象
hero=Hero()
#调用方法
hero.set_info()
#通过对象获取属性
print(hero.name,hero.age,hero.address)
#给对象添加额外属性
hero.qq='12@qq.com'
hero.email='wt_kljl.com'
# hero.print_info()
hero.__class__.print_info(hero)

image

私有属性
class Hero:
    def __init__(self):
        self.name='吕布'
        self.age=22
        self.__address='长沙'#私有属性

#创建实例对象
hero=Hero()
print(hero.age)
print(hero.__address)

image

单继承
class A:
    def __init__(self):
        self.name='吕布'
class B(A):
    pass
result=B()
print(result.name)

image

多继承
class A:
    def __init__(self):
        self.add='kkk'
    def name(self):
        name='吕布'
        print(name)
class B:
    def __init__(self):
        self.email='1.com'
    def age(self):
        age=22
        print(age)
class C(A,B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

result=C()
# result.name()
# result.age()
print(result.email)

image

重写
class A:
    def __init__(self):
        self.add='kkk'
    def name(self):
        name='吕布'
        print(name)
class B(A):
    def __init__(self):
        A.__init__(self)
        self.email='1.com'
    def name(self):
        age=22
        print(age)
result=B()
result.name()
print(result.email)

image

迭代器

from collections.abc import Iterable
from collections.abc import Iterator
class MyList:
    """自定义的一个可迭代对象"""
    def __init__(self):
        self.container=[]
    def add(self,item):
        self.container.append(item)
    def __iter__(self):
        return MyIterator()
class MyIterator:
    """自定义的迭代器"""
    def __init__(self):
        pass
    def __next__(self):
        pass
    def __iter__(self):
        pass
mylist=MyList()
mylist_iter=iter(mylist)
print('mylist是否是可以迭代对象',isinstance(mylist,Iterable))
print("mylist是否是迭代器",isinstance(mylist,Iterator))

print("mylist_iter是否是可以迭代对象",isinstance(mylist_iter,Iterable))
print("mylist_iter是否是迭代器",isinstance(mylist_iter,Iterator))

image

生成器

send和close的使用
def get_num(number):
    i=0
    while i< number:
        data=yield i
        if data=='这是测试时传递的一个值':
            print(123)
        print('data变量的值:',data)
        i+=1
obj=get_num(5)
print(obj.send(None))#第一次执行生成器时不能使用send方法去传递任何对象,除了None
print(obj.send('这是测试时传递的一个值'))
obj.close()#关闭生成器对象,后续代码无法运行生成器对象
print(next(obj))#StopIteration错误
生成器并发练习
import time
def task1():
    while True:
        print('任务1')
        yield
        time.sleep(1)#模拟I/O操作
def task2():
    while True:
        print('任务2')
        yield
        time.sleep(1)#模拟I/O操作
def scheduler():
    tasks=[task1(),task2()]#初始化任务列表
    while tasks:#循环直到没有任务剩下
        for t in tasks:
            try:
                next(t)#运行到下一个yield
            except StopIteration:
                tasks.remove(t)#任务完成则从列表中移除
#运行调度器
scheduler()

闭包

闭包初体验
def person(name):
    def say(content):
        print(f'({name}):{content}')
    print(id(say))
    return say
lubu=person('吕布')
liubei=person('刘备')
lubu('你好')
liubei('你好!')

image

装饰器

基础使用
def debug(func_obj):
    def wrapper():
        print(f'函数名称:{func_obj.__name__}')
        func_obj()
    return wrapper
@debug
def say_goodbye():
    print('hello!')
# debug_say_goodbye=debug(say_goodbye)
# debug_say_goodbye()
say_goodbye()
带参数的使用
def debug(func_obj):
    def wrapper(*args ,**kwargs):
        print(f'function_name:{func_obj.__name__}')
        func_obj(*args,**kwargs)
    return wrapper
@debug
def print_info(name,gender,address):
    print(f'姓名:{name},性别:{gender},地址:{address}')
print_info('吕布','男',address='重庆')
def log(level):
    def wrapper(func_obj):
        print(f'[{level}]:{func_obj.__name__}')
        def inner(*args,**kwargs):
            return func_obj(*args,**kwargs)
        return inner
    return wrapper
# def print_info(name,gender,address):
#     print(f'姓名:{name},性别:{gender},地址:{address}')
#     return name,gender,address
# wrapper=log('info')
# inner=wrapper(print_info)
# name,gender,address=inner('吕布','女','重庆')
# print(name,gender,address)

@log('info')
def print_info(name,gender,address):
    print(f'姓名:{name},性别:{gender},地址:{address}')
print('print_info',id(print_info))
print_info('吕布','男','重庆')
利用类实现
class Log:
    def __init__(self,func_obj):
        self.func_obj=func_obj
    def __call__(self, *args, **kwargs):
        print(f'[{self.func_obj.__name__}]')
        self.func_obj(*args,**kwargs)
@Log
def say_hello():
    print('你好!')
say_hello()
带参数的使用
class Log:
    def __init__(self, level):
        self.level = level

    def __call__(self, func_obj):
        def wrapper(*args, **kwargs):
            print(f'[{self.level}]:function_name:{func_obj.__name__}-[{args},{kwargs}]')
            func_obj(*args, **kwargs)

        print(id(wrapper))
        return wrapper


@Log(level='info')
def say_hello(name, gender, address):
    print(f'{name},{gender},{address}:你好!')

print(id(say_hello))
say_hello('吕布', '男', address='重庆')
property体验
class Pager:
    def __init__(self,current_page):
        self.current_page=current_page#用户所在的页面
        self.per_num=10#每页显示的数据数目
    @property
    def start(self):#编号起始位置
        value=(self.current_page-1)*self.per_num+1
        return value
    @property
    def end(self):#编号结束位置
        value=self.current_page*self.per_num
        return value
page=Pager(3)
print(page.start)
print(page.end)
property基础使用
class Good:
    #获取调用此方法
    @property
    def price(self):#被property装饰器装饰的函数本身也是一个装饰器
        return '@property2'
    #对方法重橷赋值调用此函数
    @price.setter
    def price(self,value):
        print(f'set方法被执行了,{value}')
    #删除方法调用此函数
    @price.deleter
    def price(self):
        print('删除被执行了...')
good=Good()
print(good.price)
good.price='1234'
del good.price

上下文管理

class Test:
    def __enter__(self):
        print(1)
        return self
    def __exit__(self,*args,**kwargs):
        print(2)
    def run(self):
        print('run...')
with Test() as t:
    t.run()

线程

初步使用
import time
import threading
def work_1():
    print('任务1。。')
    time.sleep(1)
def work_2():
    print('任务2。。')
    time.sleep(1)
#1.创建线程对象
t1=threading.Thread(target=work_1)
t2=threading.Thread(target=work_2)
#2.启动线程对象
t1.start()
t2.start()
主线程堵塞
import time
import threading
def work():
    print('这是一个任务。。')
    time.sleep(2)
t=threading.Thread(target=work)
t.start()#启动
t.join()#在子线程完成之前堵塞主线程
print('主线程退出')
设置守护线程
import time
import threading
def work():
    print('这是一个任务。。')
    time.sleep(2)
t=threading.Thread(target=work)
t.daemon=True#设置线程为守护线程
t.start()
print('主线程退出。。')
线程方法
import time
import threading
def work():
    name=threading.current_thread().getName()
    time.sleep(1)
    print(name)
for i in range(5):
    t=threading.Thread(target=work)
    # t.setName(f'线程:{i}')
    t.start()
t=threading.current_thread()#主线程
print(t.getName())
线程递归互斥锁
import threading
from threading import RLock #互斥锁:在锁被释放之前线程无法切换运行,可以连续上多次锁/解多次锁
from threading import Lock#同步互斥锁
num=0
#在全局中创建互斥锁对象
lock=RLock()
def add():
    global num
    for i in range(10000):
        lock.acquire()#上锁
        num+=1
        lock.release()#解锁
def sub():
    global num
    for i in range(10000):
        lock.acquire()
        num-=1
        lock.release()
t1=threading.Thread(target=add)
t2=threading.Thread(target=sub)
t1.start()#start只是给操作系统发送了一个启动的信号
t2.start()
t1.join()
t2.join()
print(num)
上下文管理递归互斥锁
import threading
from threading import RLock

lock = RLock()
num = 0


def add():
    global num
    for _ in range(10000):
        with lock:
            num += 1


def sub():
    global num
    for _ in range(10000):
        with lock:
            num -= 1


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=sub)
t1.start()
t2.start()
t1.join()
t2.join()
print(num)
线程池的使用
import time
from concurrent.futures import ThreadPoolExecutor,as_completed,wait
def get_html(time_attr):
    time.sleep(time_attr)#模拟网络延迟操作
    print('获取网站页数成功:',time_attr)
    return time_attr
time_attr_list=[3,1,4,2]
pool=ThreadPoolExecutor(max_workers=4)
future_list=[pool.submit(get_html,time_attr)for time_attr in time_attr_list]

# for future in future_list:#如果前一个任务没有完成则无法获取到后一个任务的返回值
#     print('任务返回值:',future.result())
# for future in as_completed(future_list):
#     #如果其中的任务已经拿到返回值则立即返回
#     print('任务返回值:',future.result())
# #将任务的参数批次传入:map批次传递参数
# results=pool.map(get_html,time_attr_list)
# for temp in results:
#     print(temp)#如果通过map的方式提交任务,则打印的返回值无需调用result方法
# wait(future_list)#让主线程堵塞
# print('主线程结束')


# #1.创建线程池对象
# pool=ThreadPoolExecutor(max_workers=1)
# #2.提交任务到线程池
# future_1=pool.submit(get_html,3)
# future_2=pool.submit(get_html,2)
# #3.如何判断提交的任务是否完成,done方法返回的是一个布尔值,True代表任务完成
# print('任务1是否完成:',future_1.done())
# #4.线程池支持取消任务,如果当前任务已经在线程池中则无法取消
# print('取消任务2:',future_2.cancel())
# #5.获取任务返回值
# print('任务1的返回值为:',future_1.result())
# #6.关闭线程池
# #pool.shutdown()#不在接收新的任务

进程

import os
import multiprocessing
import time


def work_1():
    print(f'子进程pid编号为:{os.getpid()},主进程编号为:{os.getppid()}')
    for  i in range(5):
        print('这是任务1。。')
        time.sleep(1)
def work_2():
    for i in range(5):
        print('这是任务2。。')
        time.sleep(1)

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=work_1)
    # p2 = multiprocessing.Process(target=work_2)
    p1.start()
    #在主线程中获取编号
    print('主进程:',os.getpid())
    #获取运行python程序的进程
    print('pycharm进程编号为:',os.getppid())
    # p2.start()
进程池
import os
import time
import random
from multiprocessing import Pool
def work(message):
    p_start=time.time()
    print(f'{message}开始执行,任务的进程编号为{os.getpid()}')
    time.sleep(random.random()*2)
    p_end=time.time()
    print(f'{message}执行完毕,耗时为:{p_end-p_start}')
if __name__ == '__main__':
    main_start=time.time()
    #创建进程池对象
    pool=Pool(3)
    for item in range(1,11):
        #同步传递
        pool.apply(work,(item,))
        #并发调度
        # pool.apply_async(work,(item,))
    print('---start---')
    pool.close()#关闭进程池,关闭之后进程池对象不在接收新的任务
    pool.join()#主进程等待进程池对象任务全部完成之后解堵塞,join必须在close方法之后调用
    main_end=time.time()
    print(f'主进程耗时:{main_end-main_start}')

队列

from queue import Queue
#1.创建一个队列对象
queue=Queue(6)#创建了一个队列对象并设置队列对象存储的最大长度:4个值
#2.将数据传入到队列中
queue.put(1)
queue.put(2)
#3.获取之前传递的数据
# print(queue.get())#如果队列为空会导致主线程堵塞,直到队列中存在元素才会解堵塞
#4.如果队列为空获取数据直接抛出异常
# print(queue.get_nowait())
#5.判断队列为空
# print(queue.empty())
#6.设置队列的最大存储长度
# for i in range(1,5):
#     queue.put(i)如果队列已满则无法传递新的数据到队列中,会导致堵塞
#7.如果队列已满并且不想让主线程堵塞则使用put_nowait方法
# queue.put_nowait(4)#导致主线程抛出异常
#8.判断队列是否已满
print(queue.full())
# #9.队列的特征:先进先出
# for _ in range(6):
#     print(queue.get())
# #获取到当前队列中真实的数据长度
# print('没有调用get方法时的队列长度:',queue.qsize())

协程

协程初体验
import asyncio
async def work_1():
    for _ in range(5):
        print('我是异步任务1。。。')
        await asyncio.sleep(1)
async def work_2():
    for _ in range(5):
        print('我是异步任务2。。')
        await asyncio.sleep(1)
#创建事件循环对象
loop=asyncio.get_event_loop()
#调度单个任务
# loop.run_until_complete(work_1())#调用事件循环内部的任务,当前方法接收一个协程对象
# loop.run_until_complete(loop.create_task(work_1()))
#调度多个任务
# loop.run_until_complete(asyncio.wait([work_1(),work_2()]))#传递一个列表
# loop.run_until_complete(asyncio.gather(work_1(),work_2()))#传递任务本身
新版本
# 任务启动函数
async def main():
    # 手动将任务打包成task对象
    tasks = [asyncio.create_task(work_1()), asyncio.create_task(work_2())]
    await asyncio.wait(tasks)

asyncio.run(main())
协程切换
import time
import asyncio
async def others():
    print('任务开始...')
    await asyncio.sleep(2)
    print('任务结束。。。')
    return '123'
async def main():
    print('这是协程函数的内部代码。。。')
    result_1=await others()
    print('第一次运行的返回值:',result_1)
    result_2=await others()
    print('第二次运行的返回值:',result_2)
start_time=time.time()
loop=asyncio.get_event_loop()
loop.run_until_complete(main())
end_time=time.time()
print(f'耗时:{end_time-start_time}')
task对象
import asyncio


async def others():
    print('任务开始。。。')
    await asyncio.sleep(2)
    print('任务结束。。。')
    return '1234'
async def main():
    print('这是协程函数的内部代码。。。')
    #将存储了多个协程对象的列表交给事件循环调度
    #wait方法在高版本中不接受协程对象,只接受task对象
    # work_list=[others(),others()]
    # result=await asyncio.wait(work_list)
    # print(result)

    #task 对象是一种受支持的并发对象
    # task_1=loop.create_task(others())
    # task_2=loop.create_task(others())
    # result_1=await task_1
    # print(f'task_1任务的返回值为:{result_1}')
    # result_2=await task_2
    # print(f'task_2任务的返回值为:{result_2}')

    tasks=[loop.create_task(others()) for _ in range(2)]
    results=await asyncio.gather(*tasks)#收集已经完成的任务的返回值,返回的类型是一个列表
    print('直接打印的结果:',results)
loop=asyncio.get_event_loop()
loop.run_until_complete(main())
执行多任务
import asyncio


async def others():
    print('任务开始。。。')
    await asyncio.sleep(2)
    print('任务结束。。。')
    return '1234'
async def main():
    tasks=[loop.create_task(others()) for _ in range(2)]
    done,pending=await asyncio.wait(tasks)#返回一个元组,done已完成,pending未完成
    print(done)
    print(pending)
    for i in done:
        print(i.result())#获取任务的返回值
if __name__ == '__main__':
    loop=asyncio.get_event_loop()
    loop.run_until_complete(main())
协程执行普通函数
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
def work():
    print('这是一个普通任务。。。')
    time.sleep(2)
    return '这是当前任务的返回值'
async def main():
    with ThreadPoolExecutor(max_workers=2) as pool:
        result=await loop.run_in_executor(pool,work)#事件循环对象允许执行普通任务
    return result
if __name__ == '__main__':
    loop=asyncio.get_event_loop()
    res=loop.run_until_complete(main())
    print(res)
异步迭代器
import asyncio


class Reader:
    def __init__(self):
        self.count=0
    async def read_line(self):
        self.count+=1
        if self.count==101:
            return None
        return self.count
    #普通函数
    def __aiter__(self):
        return self
    async def __anext__(self):
        value=await self.read_line()
        if value is None:
            raise StopAsyncIteration #异步迭代异常
        return value
async def main():
    async for item in Reader():
        print(item)
if __name__ == '__main__':
    loop=asyncio.get_event_loop()
    loop.run_until_complete(main())
异步生成器
import asyncio


async def work():
    for item in range(1,101):
        yield item
async def main():
    async for i in work():
        print(i)
if __name__ == '__main__':
    loop=asyncio.get_event_loop()
    loop.run_until_complete(main())
异步上下文管理
import asyncio


class AsyncContextManager:
    def __init__(self,conn=None):
        print(1)
        self.conn=conn
    async def do_something(self):
        print(3)
        return '模拟数据库异步增删除改查操作'
    async def __aenter__(self):
        print(2)
        self.conn=await asyncio.sleep(1,result='sql_connection_obj')
        print(self.conn)
        return self
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        print(4)
        result=await asyncio.sleep(1,result='close_connection_obj')
        print(result)
async def main():
    async with AsyncContextManager() as acm:
        result=await acm.do_something()
        print(result)
if __name__ == '__main__':
    loop=asyncio.get_event_loop()
    loop.run_until_complete(main())

mysql学习

查询已存的数据库
show databases;
进入到指定数据库
use 数据库名
查询数据库所在的位置
select database();

image

查询数据库版本
select version();

image

查询库中的所有表
show tables;

image

创建数据库
create database 库名 charset=utf8mb4;
删除数据库
drop database 库名;
创建表
create table stu_info(
id int primary key auto_increment,
name varchar(20) not null,
age tinyint unsigned default 0,
height decimal(5,2),
gender enum('男','女','未知','人妖'),
cls_id int unsigned default 0
);
查询表结构
desc 表名;
···
![image](https://img2024.cnblogs.com/blog/3081830/202403/3081830-20240307224619769-1848440622.png)
#####添加字段
```sql
alter table stu_info add birthday datetime;

image

修改字段名称-字段名称与类型

···sql
alter table stu_info change birthday brith date not null;

![image](https://img2024.cnblogs.com/blog/3081830/202403/3081830-20240307225448847-770265945.png)
#####修改字段类型 -无需修改字段名称时使用
```sql
alter table stu_info modify brith time unique;

image

删除多余字段
alter table stu_info drop brith;
···
![image](https://img2024.cnblogs.com/blog/3081830/202403/3081830-20240307230434670-198058332.png)
#####查询表的创建过程
```sql
show create table stu_info;
表插入
表的创建
create table students(
id int unsigned primary key auto_increment not null,
name varchar(20) default '',
age tinyint unsigned default 0,
heigth decimal(5,2),
gender enum('男','女','中性','保密') default '保密',
cls_id int unsigned default 0,
is_delete bit default 0
)
create table classes(
id int unsigned auto_increment primary key not null,
name varchar(20) not null
)
全部数据插入
insert into students values(0,'吕布',23,123.22,'男',1,0);
insert into students values(null,'刘备',11,121.11,'男',2,0);
insert into students values(default,'张飞',22,231.11,'男',2,0);
insert into students values(0,'孙策',22,123.44,'男',1,0),(0,'曹操',33,231.22,'男',1,0);
部分数据插入
insert into students(id,name,height) values(0,'孙尚香');
修改数据
update students set age=24 where id=4;--不添加条件会修改全部数据
删除数据
物理删除
delete select * from students where age=4;--删除了无法恢复
逻辑删除
update students set is_delete=1 where age=1;
数据准备
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);

insert into classes values (0, "python_01期"), (0, "python_02期");
#####字段别名
select id as 编号,name as 学生性名 from students;

image

数据去重
select distinct gender from students;

image

条件查询

比较运算
select * from students where id<3;

image

逻辑运算
select * from students where id<4 and gender='男';

image

模糊查询
select * from students where name='周%';
select * from students where name='周__';

image

范围查询

非连续范围查询
select * from students where name in ('黄蓉','周杰','周杰伦');

image

连续范围查询
select * from students where id between 3 and 8;

image

空判断

select * from students wherer height is null;

image

排序

select * from student order by id desc;

image

聚合函数

select count(*) from students;

image

分组查询

select gender,group_concat(name) from students group by gender;

image

分组后使用条件
selcet gender ,count(*) from students group by gender having count(*)>=2;

image

新增一行统计所有值
select gender,group_concat(age) from students group by grender with rollup;

image

分页

select * from students limit 0,3;

image

内连接

select * from students inner join classes on students.cls=classes.id;

image

左右连接

select * from students as 学生表 left join calsses as 班级表 on 学生表.cls_id=班级表.id;
select * from students as 学生表 right join calsses as 班级表 on 学生表.cls_id=班级表.id;

image
image

自关联

--查询省的总数信息
select count(*) from tb_areas where pid is null;
--查询湖南省id编号
select aid from tb_areas where aitile='湖南省';
select * from tb_areas where pid=430_000;
select * from tb_areas where pid=430_100;

--查询城讪信息,并链接到省信息[self table】],链接查询条件为pid=aid,设定省信息为湖南省;
select 城市信息.* from tb_areas as 城市信息 inner join tb_areas as 省信息 on 城市信息.pid=省信息.aid where 省信息.aitile='湖南省';
select 区县信息.* from tb_areas as 区县信息 inner join tb_areas as 城市信息 on 区县信息.pid=城市信息.aid where 省信息.aitile='长沙市';

子查询

select avg(age) from students;
select * from students where age> (select avg(age) from students);

视图

创建视图

create view v_select_city as  select 区县信息.* from tb_areas as 区县信息 inner join tb_areas as 城市信息 on 区县信息.pid=城市信息.aid where 城市信息.aitile='长沙市';

查询创建视图信息

select * from v_select_city;
删除视图
drop view v_select_city;

image

事务

begin;--开启事务
commit;--提交事务
rollback;--回滚;恢复到开启事务之前的状态

pymysql的使用

import pymysql

def db_connect():
    #1.数据库链接对象
    db=pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')
    #2.创建游标,执行sql语句
    cursor=db.cursor()
    #3.执行sql
    cursor.execute('select version();')
    result=cursor.fetchone()#返回的结果为一个元组
    print(result[0])
    #4.关闭游标对象与数据库链接对象
    cursor.close()
    db.close()
if __name__ == '__main__':
    db_connect()

image

上下文管理pymysql

import pymysql
def create_table():
    with pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')as db:
        with db.cursor()as cursor:
            cursor.execute('drop table if exists employee;')
            sql="""
            create table employee(
                first_name varchar(20) not null,
                last_name varchar(20) ,
                age tinyint ,
                sex enum('男','女'),
                income float,
                create_time datetime
            );
            """
            try:
                cursor.execute(sql)
                print('创建表成功。。。')
            except Exception as e:
                print('创建表失败。。。')
if __name__ == '__main__':
    create_table()

image

插入数据

import datetime
import pymysql
def insert_info():
    db=pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')
    cursor=db.cursor()
    sql="""
    insert into employee(first_name,last_name,age,sex,income,create_time)values(
    %s,%s,%s,%s,%s,%s
    );
    """
    try:
        info=('吕','布',12,'男',123,datetime.datetime.now())
        cursor.execute(sql,info)
        db.commit()
        print('数据插入成功')
    except Exception as e:
        print('插入数据失败。。。')
        db.rollback()
    finally:
        cursor.close()
        db.close()
if __name__ == '__main__':
    insert_info()

image

查询数据

import pymysql
def search_info():
    db=pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')
    cursor=db.cursor()
    sql='select * from employee where income >%d'%12
    try:
        cursor.execute(sql)
        result=cursor.fetchall()
        for row in result:
            for val in row:
                print(val)

    except Exception as e :
        print('数据查询失败:',e)
    finally:
        cursor.close()
        db.close()
if __name__ == '__main__':
    search_info()

image

数据更新

import pymysql
def update_info():
    db=pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')
    cursor=db.cursor()
    sql='update employee set age=age+1 where sex="女"'
    try:
        cursor.execute(sql)
        db.commit()
        print('数据更新成功。。。')
    except Exception as e:
        print('数据更新失败。。。')
        db.rollback()
    finally:
        cursor.close()
        db.close()
if __name__ == '__main__':
    update_info()

image

删除数据

import pymysql
def delete_info():
    db=pymysql.connect(host='localhost',port=3306,user='root',password='root',db='python_test_1')
    cursor=db.cursor()
    sql='delete from employee where age >1'
    try:
        cursor.execute(sql)
        db.commit()
        print('删除数据成功。。。')
    except Exception as e:
        db.rollback()
        print('删除数据失败',e)
    finally:
        cursor.close()
        db.close()
if __name__ == '__main__':
    delete_info()

redis学习

链接服务

redis-cli

image

测试

ping

image

str类型

保存字符串

set name liubu

image

获取字符串

get name

image

设置带有过期时间的字符串

setex name 5 abc

image

批量保存多个字符串

mset name aa age 10 gender male

image

批量获取多个字符串

mget name age gender

image

查询数据库中的key

keys n*

image

判断指字的键是否在数据库中

exists name

image

判断键对应的类型

type name

image

删除键值对

del name

image

hash类型

储存单个field

hset stu_info name bb

image

储存多个field

hmset stu_info name cc age 18

image

获取所有field

hkeys stu_info

image

单个获取field

hget stu_info name

image

多个获取field

hmget stu_info name age

image

获取所有的value,不需要指定

hvals stu_info

image

删除

hdel stu_info name
hmdel stu_info age name
del stu_info

列表类型

左右插入

lpush name_1 a b c
rpush name_2 a b c
···
###获取
```txt
lrange name_1 0 -1
lrange name_2 0 -1

image

删除

lpush test_list a b a b a b
lrange test_list 0 -1
lrem test_list -2 b
lrange test_list 0 -1

image

集合类型

无序集合

增加

sadd user_name liubei liubu

获取

smembers user_name

image

删除

删除指定元素
srem user_name liubu
删除整个类型
del user_name

image

查看类型

type user_name

image

有序集合

添加

zadd user_name_1 4 a 8 b 1 c 3 d

image

查询

zrange user_name 0 -1

image

删除

zrem user_name_1 c #指定
del user_name

image

python连接redis

from redis import Redis
with Redis() as db:
    print(db)
    #增
    result=db.set('stu_name','吕布')
    print(result)
    #查
    result2=db.get('stu_name')
    print(result2.decode('utf-8'))
    #改
    result3=db.set('stu_name','诸葛亮')
    print(db.get('stu_name').decode('utf-8'))
    #删
    result4=db.delete('stu_name')
    print(result4)
    print(db.keys())

image

mongodb学习

下载

数据库

查看数据库

show dbs/show database

查看当前数据库

db

切换数据库

use 数据库名

删除哦数据库

db.dropDatabase()

集合

创建

db.createCollection('stu')
#插入数据
db.stu.insert({'name':'kk'})
#更新数据
db.stu.update({'name':'kk'},{'name':'00'})

查看

show.collections
#查看数据
db.stu.find()

删除

db.stu.drop()
#删除数据
db.stu.remove({'name':'00'})
posted @ 2024-03-27 10:08  自由的飞翔666  阅读(51)  评论(0)    收藏  举报