python - 菜鸟练习
`# 九九乘法口诀
print("========================= 九九乘法口诀 =========================")
v_re = 0
for i in range(1, 10):
for j in range(i, 10):
v_re = i * j
print(str(i) + ' x ' + str(j) + ' = ' + str(v_re), end='\t')
print(" ")
print("================================================================")
# 列表求和
print("=========================== 列表求和 ===========================")
sn = 0
v_lst = [1, 2, [5,9], 12, 34, [1,2,3], 55]
for i in v_lst:
if type(i) == list:
for j in i:
sn += j
else:
sn += i
print(sn, end='\n')
print("================================================================")
# 超市购物
print("=========================== 超市购物 ===========================")
'''
v_lst = [[1, '电脑', 1999, 5], [2, '鼠标', 10, 5], [3, '键盘', 20, 5], [4, 'CPU', 998, 5]]
for v_item in v_lst:
print('序号:' + str(v_item[0]) + ',产品:' + v_item[1] + ',单价:' + str(v_item[2]) +',库存:' + str(v_item[3]))
while(1):
v_buy = list(input('请输入你要买的产品的序号(1~4)和数量(小于库存)'))
print(type(v_buy))
if not isinstance(v_buy[0], int) or v_buy[0] < 1 or v_buy[0] > 4:
print(v_buy[0])
#print("数值非法, 退出程序")
#break
else:
print("数值合法")
'''
print("================================================================")
# 年月日判断
print("=========================== 年月日判断 =========================")
#v_value= input("请输入年月份,格式YYYY-MM-DD:")
v_value = '2026-08-10'
v_year = int(v_value[0:4])
v_mon = int(v_value[5:7])
v_day = int(v_value[9:10])
mon_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (v_year % 4 == 0 and v_year % 100 != 0) or v_year % 400 == 0:
mon_days[1]=29
day = sum(mon_days[:v_mon -1]) + v_day
print(day)
print("================================================================")
# 二手车停车系统
print("========================= 二手车停车系统 =======================")
cnt=0
print('''0:退出程序:
1:新进一辆车:
2:出库一辆车:
3:显示车辆库存信息:
4:显示某品牌剩余库存:
''')
lst = [['朗逸', 5], ['帕萨特', 5], ['桑塔拉', 5], ['捷达', 5], ['高尔夫', 5], ['POLO', 5], ['迈腾', 5]]
#num = int(input('请输入序号:'))
num = 3
if num == 0:
exit()
elif num == 1:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
i[1] += 1
print(i[1])
elif num == 2:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
i[1] -= 1
print(i[1])
elif num == 3:
for i in lst:
cnt += i[1]
print(cnt)
elif num == 4:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
print(i[1])
else:
pass
#print(lst)
print("================================================================")
# 反向对查找
print("========================== 反向对查找 ==========================")
words = '''For a long time, I have been trying to fit myself into other people’s expectations, chasing perfection that never truly on to me. I used to fear failure, level judgment, and fear that I was not good enough to be seen and loved. I kept silent about my true feelings, compromised my boundaries, and hurried through every day, just to become the eye others admired. But gradually, I felt exhausted and empty inside.
'''
for i in words.split(' '):
if i[::-1] in words:
print(i, i[::-1])
print("================================================================")
# 随机数排序
print("========================== 随机数排序 ==========================")
import random
lst = [random.randint(0, 100) for i in range(100)]
lst1 = lst[:10]
lst1.sort()
lst2 = lst[-10:]
lst2.sort(reverse=True)
print(lst1, lst2)
print("================================================================")
# 体重计算
print("=========================== 体重计算 ===========================")
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
while(1):
break
v_q = input('请输入体重(kg),输入Q退出: ')
if v_q.lower() == 'q':
exit()
elif is_number(v_q) is False:
print('输入有误, 请重新输入~')
continue
#地球
lst1 = [float(v_q) + 0.5 * x for x in range(10)]
#月球
lst2 = [float(v_q) * 0.165 + 0.5 * x for x in range(10)]
print(lst1, lst2)
print("================================================================")
# 杨辉三角
print("=========================== 杨辉三角 ===========================")
def yh():
ls = [1]
while 1:
yield ls
ls = [(ls[i] + ls[i-1]) for i in range(1,len(ls))]
ls.insert(0, 1)
ls.append(1)
m = yh()
for _ in range(10):
x = next(m)
print(x)
print("================================================================")
# 汉诺塔问题
print("========================== 汉诺塔问题 ==========================")
def move(num, a, b, c):
if num == 1:
print(a, '---->', c)
else:
# 把n‑1个,a借助c移到b
move(num - 1, a, c, b)
# 最大盘 a→c
print(a, '---->', c)
# 把n‑1个,b借助a移到c
move(num - 1, b, a, c)
v_num = int(input('需要移动的盘子数是: '))
move(v_num, 'A', 'B', 'C')
print("================================================================")
# 发红包
print("========================== 发红包 ==========================")
import random as r
ls = []
s = 10
for i in range(7):
n = round(r.uniform(0, 1) * s, 2)
if n <= 0.00:
n = 0.01
s = s - n - 0.1
ls.append(n)
a = round(10 - sum(ls),2)
ls.append(a)
r.shuffle(ls)
print(max(ls))
print(min(ls))
print(ls)
print("================================================================")
# csv读取
print("========================== csv读取 ==========================")
import csv
f =open('test.csv', 'r', newline='')
r = csv.reader(f)
ls = []
for i in r:
print(i)
f.close()
print("================================================================")
# csv写入
print("=========================== csv写入 ============================")
import csv
ls = [(1701, '张三', '男', 88),
(1702, '莉莉', '女', 96),
(1703, 'Tom', '男', 90),
(1704, '李晨', '女', 99),
(1705, '王伟', '男', 82)]
ls.sort(key=lambda x:x[3]) # 按分数排序
f = open('test.csv', 'w+', newline='') ## win换行\r\n : linux \n
w = csv.writer(f)
for i in ls:
w.writerow(i)
f.close()
print("================================================================")
# 冒泡排序 BubbleSort
print("========================== 冒泡排序 ============================")
ls = [1, 8, 6, 4, 9, 2, 33, 45, 12, 56]
for i in range(len(ls)):
for j in range(len(ls) - 1):
if ls[i] < ls[j]:
ls[i], ls[j] = ls[j], ls[i]
print(ls)
print("================================================================")
# 选择排序 SelectSort
print("========================== 选择排序 ============================")
ls = [1, 8, 6, 4, 9, 2, 33, 45, 12, 56]
ln = []
while ls:
m = min(ls)
i = ls.index(m)
ln.append(ls.pop(i))
print(ln)
print("================================================================")
# 插入排序 InsertSort
print("========================== 插入排序 ============================")
ls = [11, 8, 6, 4, 9, 2, 33, 45, 12, 56]
ln = []
ln.insert(0, ls[0])
ls.pop(0)
for m in ls:
f = False
for i in range(len(ln)):
if m < ln[i]:
ln.insert(i, m)
f = True
break
if not f:
ln.append(m)
print(ln)
print("================================================================")
# class矩形计算
print("======================= class矩形计算 ==========================")
class Rectangle:
def __init__(self, w=1, h=2):
self.w = w
self.h = h
def getArea(self):
return self.w * self.h
def getPerimeter(self):
return 2*(self.w + self.h)
p1 = Rectangle(4, 40)
print('宽:' , p1.w, ' 高:' , p1.h, ' 面积:', p1.getArea(), ' 周长:', p1.getPerimeter())
p1 = Rectangle(3.5, 35)
print('宽:' , p1.w, ' 高:' , p1.h, ' 面积:', p1.getArea(), ' 周长:', p1.getPerimeter())
print("================================================================")
# sqlite建表
print("========================= sqlite建表 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
sql_tab = 'drop table if exists my_tab'
cur.execute(sql_tab)
sql_tab = 'create table my_tab(c1 int, c2 varchar(20), c3 int)'
cur.execute(sql_tab)
conn.close()
print("================================================================")
# sqlite插数
print("========================= sqlite插数 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
lst = [(1, '张三', 1), (2, '李四', 1), (3, '王五', 2)]
sql_into = 'insert into my_tab values (?,?,?)'
cur.executemany(sql_into, lst)
conn.commit()
conn.close()
print("================================================================")
# sqlite查询
print("========================= sqlite查询 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
for i in rows:
print(i)
conn.close()
##====== 更改
import sqlite3 as sq
conn = sq.connect(r'E:\ai\python\my.db')
cur = conn.cursor()
sql_upset = "update my_tab set c2 = '赵六' where c1 = 3"
cur.execute(sql_upset)
conn.commit()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
conn.close()
##====== 删除
import sqlite3 as sq
conn = sq.connect(r'E:\ai\python\my.db')
cur = conn.cursor()
sql_del = "delete from my_tab where c1 = 3"
cur.execute(sql_del)
conn.commit()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
conn.close()
print("================================================================")
# 做蛋糕,吃蛋糕,不太会,豆包写的
print("======================= 做蛋糕,吃蛋糕 =========================")
import threading
import time
lock = threading.Lock()
fridge = [] # 冰箱存放蛋糕
total_cake = 20 # 一共要做20个
def mom():
"""妈妈:生产者,做蛋糕"""
for i in range(1, total_cake + 1):
time.sleep(0.3) # 做一个耗时0.3秒
with lock:
fridge.append(i)
print(f"👩妈妈做好第{i}个蛋糕,放进冰箱,冰箱现有:{fridge}")
def son():
"""儿子:消费者, 吃蛋糕"""
eaten = 0
while eaten < total_cake:
with lock:
if fridge:
cake = fridge.pop(0)
eaten += 1
print(f"👦儿子拿到第{cake}个蛋糕,开始吃,冰箱剩余:{fridge}")
else:
print(f"😭儿子拿不到蛋糕,哭了!冰箱为空")
time.sleep(0.2) # 吃蛋糕耗时0.2秒
print("✅儿子吃完全部20个蛋糕,结束!")
if __name__ == "__main__":
t_mom = threading.Thread(target=mom)
t_son = threading.Thread(target=son)
t_mom.start()
t_son.start()
t_mom.join()
t_son.join()
##===============
import threading
import time
from queue import Queue, Empty
q = Queue()
TOTAL_CAKE = 20 # 总共20个蛋糕
def mom_producer():
"""妈妈生产者:0.3秒做1个蛋糕"""
for cake_id in range(1, TOTAL_CAKE + 1):
time.sleep(0.3)
q.put(cake_id)
print(f"👩妈妈做好第{cake_id}个蛋糕,放入冰箱(队列),当前队列大小:{q.qsize()}")
def son_consumer():
"""儿子消费者:0.2秒吃一个,拿不到就哭"""
eat_count = 0
while eat_count < TOTAL_CAKE:
try:
# block=False 不阻塞,没有蛋糕直接抛Empty异常
cake = q.get(block=False)
eat_count += 1
print(f"👦儿子拿到第{cake}个蛋糕吃掉,剩余蛋糕数量:{q.qsize()}")
except Empty:
print(f"😭儿子拿不到蛋糕,哭了!冰箱空了")
time.sleep(0.2) # 吃蛋糕耗时
print("✅儿子吃完全部20个蛋糕,任务结束!")
if __name__ == '__main__':
t_mom = threading.Thread(target=mom_producer)
t_son = threading.Thread(target=son_consumer)
t_mom.start()
t_son.start()
t_mom.join()
t_son.join()
print("================================================================")
# 线程&进程
print("========================= 线程&进程 ============================")
import random
import threading
result = []
def computer():
# CPU密集计算:生成100万随机数求和
result.append(sum([random.randint(1,100) for i in range(1000000)]))
# 创建8个线程
workers = [threading.Thread(target=computer) for x in range(8)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print('Result :', result)
##====================
import multiprocessing
import random
def computer(n):
return sum([random.randint(1,100) for i in range(1000000)])
pool = multiprocessing.Pool(8)
print('Result:', pool.map(computer, range(8)))
print("================================================================")
# 爬虫
print("============================ 爬虫 ==============================")
from urllib import request
from bs4 import BeautifulSoup
import re
url = 'https://www.tianqihoubao.com/lishi/xian/month/202609.html'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
req_obj = request.Request(url, headers=headers)
req = request.urlopen(req_obj)
t_content = req.read().decode('utf-8')
sp = BeautifulSoup(t_content,'html.parser')
tab = sp.find_all('tbody')
for tb in tab:
tr = tb.find_all('tr')
for i in range(1, len(tr)):
td = tr[i].find_all('td')
for i in td:
tx = re.sub('\s+','',i.get_text())
print(tx, end='\t')
print('')
print("================================================================")
`
<details>
<summary>点击查看代码</summary>
`# 九九乘法口诀
print("========================= 九九乘法口诀 =")
v_re = 0
for i in range(1, 10):
for j in range(i, 10):
v_re = i * j
print(str(i) + ' x ' + str(j) + ' = ' + str(v_re), end='\t')
print(" ")
print("========================================")
列表求和
print("=========================== 列表求和 =")
sn = 0
v_lst = [1, 2, [5,9], 12, 34, [1,2,3], 55]
for i in v_lst:
if type(i) == list:
for j in i:
sn += j
else:
sn += i
print(sn, end='\n')
print("======================================")
超市购物
print("=========================== 超市购物 ===========================")
'''
v_lst = [[1, '电脑', 1999, 5], [2, '鼠标', 10, 5], [3, '键盘', 20, 5], [4, 'CPU', 998, 5]]
for v_item in v_lst:
print('序号:' + str(v_item[0]) + ',产品:' + v_item[1] + ',单价:' + str(v_item[2]) +',库存:' + str(v_item[3]))
while(1):
v_buy = list(input('请输入你要买的产品的序号(1~4)和数量(小于库存)'))
print(type(v_buy))
if not isinstance(v_buy[0], int) or v_buy[0] < 1 or v_buy[0] > 4:
print(v_buy[0])
#print("数值非法, 退出程序")
#break
else:
print("数值合法")
'''
print("================================================================")
年月日判断
print("=========================== 年月日判断 =========================")
v_value= input("请输入年月份,格式YYYY-MM-DD:")
v_value = '2026-08-10'
v_year = int(v_value[0:4])
v_mon = int(v_value[5:7])
v_day = int(v_value[9:10])
mon_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (v_year % 4 == 0 and v_year % 100 != 0) or v_year % 400 == 0:
mon_days[1]=29
day = sum(mon_days[:v_mon -1]) + v_day
print(day)
print("================================================================")
二手车停车系统
print("========================= 二手车停车系统 =======================")
cnt=0
print('''0:退出程序:
1:新进一辆车:
2:出库一辆车:
3:显示车辆库存信息:
4:显示某品牌剩余库存:
''')
lst = [['朗逸', 5], ['帕萨特', 5], ['桑塔拉', 5], ['捷达', 5], ['高尔夫', 5], ['POLO', 5], ['迈腾', 5]]
num = int(input('请输入序号:'))
num = 3
if num == 0:
exit()
elif num == 1:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
i[1] += 1
print(i[1])
elif num == 2:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
i[1] -= 1
print(i[1])
elif num == 3:
for i in lst:
cnt += i[1]
print(cnt)
elif num == 4:
st = input('请输入汽车品牌: ')
for i in lst:
if i[0] == st:
print(i[1])
else:
pass
print(lst)
print("================================================================")
反向对查找
print("========================== 反向对查找 ==========================")
words = '''For a long time, I have been trying to fit myself into other people’s expectations, chasing perfection that never truly on to me. I used to fear failure, level judgment, and fear that I was not good enough to be seen and loved. I kept silent about my true feelings, compromised my boundaries, and hurried through every day, just to become the eye others admired. But gradually, I felt exhausted and empty inside.
'''
for i in words.split(' '):
if i[::-1] in words:
print(i, i[::-1])
print("================================================================")
随机数排序
print("========================== 随机数排序 ==========================")
import random
lst = [random.randint(0, 100) for i in range(100)]
lst1 = lst[:10]
lst1.sort()
lst2 = lst[-10:]
lst2.sort(reverse=True)
print(lst1, lst2)
print("================================================================")
体重计算
print("=========================== 体重计算 ===========================")
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
while(1):
break
v_q = input('请输入体重(kg),输入Q退出: ')
if v_q.lower() == 'q':
exit()
elif is_number(v_q) is False:
print('输入有误, 请重新输入~')
continue
地球
lst1 = [float(v_q) + 0.5 * x for x in range(10)]
#月球
lst2 = [float(v_q) * 0.165 + 0.5 * x for x in range(10)]
print(lst1, lst2)
print("================================================================")
杨辉三角
print("=========================== 杨辉三角 ===========================")
def yh():
ls = [1]
while 1:
yield ls
ls = [(ls[i] + ls[i-1]) for i in range(1,len(ls))]
ls.insert(0, 1)
ls.append(1)
m = yh()
for _ in range(10):
x = next(m)
print(x)
print("================================================================")
汉诺塔问题
print("========================== 汉诺塔问题 ==========================")
def move(num, a, b, c):
if num == 1:
print(a, '---->', c)
else:
# 把n‑1个,a借助c移到b
move(num - 1, a, c, b)
# 最大盘 a→c
print(a, '---->', c)
# 把n‑1个,b借助a移到c
move(num - 1, b, a, c)
v_num = int(input('需要移动的盘子数是: '))
move(v_num, 'A', 'B', 'C')
print("================================================================")
发红包
print("========================== 发红包 ==========================")
import random as r
ls = []
s = 10
for i in range(7):
n = round(r.uniform(0, 1) * s, 2)
if n <= 0.00:
n = 0.01
s = s - n - 0.1
ls.append(n)
a = round(10 - sum(ls),2)
ls.append(a)
r.shuffle(ls)
print(max(ls))
print(min(ls))
print(ls)
print("================================================================")
csv读取
print("========================== csv读取 ==========================")
import csv
f =open('test.csv', 'r', newline='')
r = csv.reader(f)
ls = []
for i in r:
print(i)
f.close()
print("================================================================")
csv写入
print("=========================== csv写入 ============================")
import csv
ls = [(1701, '张三', '男', 88),
(1702, '莉莉', '女', 96),
(1703, 'Tom', '男', 90),
(1704, '李晨', '女', 99),
(1705, '王伟', '男', 82)]
ls.sort(key=lambda x:x[3]) # 按分数排序
f = open('test.csv', 'w+', newline='') ## win换行\r\n : linux \n
w = csv.writer(f)
for i in ls:
w.writerow(i)
f.close()
print("================================================================")
冒泡排序 BubbleSort
print("========================== 冒泡排序 ============================")
冒泡排序
ls = [1, 8, 6, 4, 9, 2, 33, 45, 12, 56]
for i in range(len(ls)):
for j in range(len(ls) - 1):
if ls[i] < ls[j]:
ls[i], ls[j] = ls[j], ls[i]
print(ls)
print("================================================================")
选择排序 SelectSort
print("========================== 选择排序 ============================")
ls = [1, 8, 6, 4, 9, 2, 33, 45, 12, 56]
ln = []
while ls:
m = min(ls)
i = ls.index(m)
ln.append(ls.pop(i))
print(ln)
print("================================================================")
插入排序 InsertSort
print("========================== 插入排序 ============================")
ls = [11, 8, 6, 4, 9, 2, 33, 45, 12, 56]
ln = []
ln.insert(0, ls[0])
ls.pop(0)
for m in ls:
f = False
for i in range(len(ln)):
if m < ln[i]:
ln.insert(i, m)
f = True
break
if not f:
ln.append(m)
print(ln)
print("================================================================")
class矩形计算
print("======================= class矩形计算 ==========================")
class Rectangle:
def init(self, w=1, h=2):
self.w = w
self.h = h
def getArea(self):
return self.w * self.h
def getPerimeter(self):
return 2*(self.w + self.h)
p1 = Rectangle(4, 40)
print('宽:' , p1.w, ' 高:' , p1.h, ' 面积:', p1.getArea(), ' 周长:', p1.getPerimeter())
p1 = Rectangle(3.5, 35)
print('宽:' , p1.w, ' 高:' , p1.h, ' 面积:', p1.getArea(), ' 周长:', p1.getPerimeter())
print("================================================================")
sqlite建表
print("========================= sqlite建表 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
sql_tab = 'drop table if exists my_tab'
cur.execute(sql_tab)
sql_tab = 'create table my_tab(c1 int, c2 varchar(20), c3 int)'
cur.execute(sql_tab)
conn.close()
print("================================================================")
sqlite插数
print("========================= sqlite插数 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
lst = [(1, '张三', 1), (2, '李四', 1), (3, '王五', 2)]
sql_into = 'insert into my_tab values (?,?,?)'
cur.executemany(sql_into, lst)
conn.commit()
conn.close()
print("================================================================")
sqlite查询
print("========================= sqlite查询 ===========================")
import sqlite3 as sq
conn = sq.connect('my.db')
cur = conn.cursor()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
for i in rows:
print(i)
conn.close()
更改
import sqlite3 as sq
conn = sq.connect(r'E:\ai\python\my.db')
cur = conn.cursor()
sql_upset = "update my_tab set c2 = '赵六' where c1 = 3"
cur.execute(sql_upset)
conn.commit()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
conn.close()
删除
import sqlite3 as sq
conn = sq.connect(r'E:\ai\python\my.db')
cur = conn.cursor()
sql_del = "delete from my_tab where c1 = 3"
cur.execute(sql_del)
conn.commit()
sql_sel= 'select * from my_tab'
cur.execute(sql_sel)
rows = cur.fetchall()
print(rows)
conn.close()
print("================================================================")
做蛋糕,吃蛋糕
print("======================= 做蛋糕,吃蛋糕 =========================")
import threading
import time
lock = threading.Lock()
fridge = [] # 冰箱存放蛋糕
total_cake = 20 # 一共要做20个
def mom():
"""妈妈:生产者,做蛋糕"""
for i in range(1, total_cake + 1):
time.sleep(0.3) # 做一个耗时0.3秒
with lock:
fridge.append(i)
print(f"👩妈妈做好第{i}个蛋糕,放进冰箱,冰箱现有:{fridge}")
def son():
"""儿子:消费者, 吃蛋糕"""
eaten = 0
while eaten < total_cake:
with lock:
if fridge:
cake = fridge.pop(0)
eaten += 1
print(f"👦儿子拿到第{cake}个蛋糕,开始吃,冰箱剩余:{fridge}")
else:
print(f"😭儿子拿不到蛋糕,哭了!冰箱为空")
time.sleep(0.2) # 吃蛋糕耗时0.2秒
print("✅儿子吃完全部20个蛋糕,结束!")
if name == "main":
t_mom = threading.Thread(target=mom)
t_son = threading.Thread(target=son)
t_mom.start()
t_son.start()
t_mom.join()
t_son.join()
===============
import threading
import time
from queue import Queue, Empty
q = Queue()
TOTAL_CAKE = 20 # 总共20个蛋糕
def mom_producer():
"""妈妈生产者:0.3秒做1个蛋糕"""
for cake_id in range(1, TOTAL_CAKE + 1):
time.sleep(0.3)
q.put(cake_id)
print(f"👩妈妈做好第{cake_id}个蛋糕,放入冰箱(队列),当前队列大小:{q.qsize()}")
def son_consumer():
"""儿子消费者:0.2秒吃一个,拿不到就哭"""
eat_count = 0
while eat_count < TOTAL_CAKE:
try:
# block=False 不阻塞,没有蛋糕直接抛Empty异常
cake = q.get(block=False)
eat_count += 1
print(f"👦儿子拿到第{cake}个蛋糕吃掉,剩余蛋糕数量:{q.qsize()}")
except Empty:
print(f"😭儿子拿不到蛋糕,哭了!冰箱空了")
time.sleep(0.2) # 吃蛋糕耗时
print("✅儿子吃完全部20个蛋糕,任务结束!")
if name == 'main':
t_mom = threading.Thread(target=mom_producer)
t_son = threading.Thread(target=son_consumer)
t_mom.start()
t_son.start()
t_mom.join()
t_son.join()
print("================================================================")
线程&进程
print("========================= 线程&进程 ============================")
import random
import threading
result = []
def computer():
# CPU密集计算:生成100万随机数求和
result.append(sum([random.randint(1,100) for i in range(1000000)]))
创建8个线程
workers = [threading.Thread(target=computer) for x in range(8)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print('Result :', result)
====================
import multiprocessing
import random
def computer(n):
return sum([random.randint(1,100) for i in range(1000000)])
pool = multiprocessing.Pool(8)
print('Result:', pool.map(computer, range(8)))
print("================================================================")
爬虫
print("============================ 爬虫 ==============================")
from urllib import request
from bs4 import BeautifulSoup
import re
url = 'https://www.tianqihoubao.com/lishi/xian/month/202609.html'
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
req_obj = request.Request(url, headers=headers)
req = request.urlopen(req_obj)
t_content = req.read().decode('utf-8')
sp = BeautifulSoup(t_content,'html.parser')
tab = sp.find_all('tbody')
for tb in tab:
tr = tb.find_all('tr')
for i in range(1, len(tr)):
td = tr[i].find_all('td')
for i in td:
tx = re.sub('\s+','',i.get_text())
print(tx, end='\t')
print('')
print("================================================================")
`

浙公网安备 33010602011771号