pei_blog

导航

 

一、笔记大纲

 

 

二、day4作业

2.1需求:

写一个商品管理的程序,数据在product.json 里面
1、4个功能,增、删、改、查
1、新增
输入 商品名称、价格、数量
商品不存在才可以添加
价格必须是大于0的整数/小数
数量必须是大于0的整数
2、查询
如果输入的是all,那么print 所有商品的信息
如果输入的是商品名称,打印某个商品的信息
如果输入为的商品名称不存在,那么提示
3、删除,输入商品名称,存在就删除
4、修改
输入 商品名称、价格、数量
商品存在才可以修改
价格必须是大于0的整数/小数
数量必须是大于0的整数
choice = input("请输入你的选择:1、 查询商品 2新增产品 3修改商品新 4、删除商品 5、退出")

2.2代码:

import json
# 文件操作
FILE_NAME="product.json"
def op_file(file_name=FILE_NAME, content=None):
with open(file_name,"a+",encoding="utf-8") as f:
# 移动文件指针到最前面,原因为a+指针在文件末尾,操作时需要现将文件指针移动到开始位置
f.seek(0)
# 传入内容时: 为写操作
if content:
# 写操作需要现将原内容清空
f.truncate()
# 将content写入文件中
json.dump(content,f)
# 传入文件为空时,为读取操作
else:
content= f.read()
#加强校验 防止空文件
if content:
return json.loads(content)
# 文件为空时,返回一个空字典
return {}
# 数字判断:大于0的正整数
def is_count(count):
# 格式转化
count=str(count)
#是数字 并且大于0
if count.isdigit() and int(count)>0:
return True

# 判断价格:大于0的整数或者小数
def is_price(price):
#格式转化
price=str(price)
# 判断是小数的情况
if price.count(".")==1:
left,right=price.split(".")
# 小数点两边都是数字
if left.isdigit() and right.isdigit():
# 是小数时,判断是否为0.0的情况
return float(price)>0
# 判断是整数的情况,使用价格判断即可
return is_count(price)
# 增加商品
def add():
name=input("name:").strip()
price=input("price:").strip()
count=input("count:").strip()
# 输入不能为空判断
if not name or not price or not count:
print("输入不能为空")
# 价格判断
elif not is_price(price):
print("价格必须为大于0的数字")
# 数量判断
elif not is_count(count):
print("数量必须为大于0的正整数")
# 数量价格 检验成功后,判断商品是否存在
else:
# 读取到的是一个字典
products = op_file()
if name in products:
print("商品已存在")
else:
# 将添加商品内容写入的字典中然后 在写入文件中
products[name]={"price":float(price),"count":int(count)}
op_file(content=products)
print("添加成功")

# 编辑商品
def update():
name = input("name:").strip()
price = input("price:").strip()
count = input("count:").strip()
# 输入不能为空判断
if not name or not price or not count:
print("输入不能为空")
# 价格判断
elif not is_price(price):
print("价格必须为大于0的数字")
# 数量判断
elif not is_count(count):
print("数量必须为大于0的正整数")
# 数量价格 检验成功后,判断商品是否存在
else:
# 读取到的是一个字典
products = op_file()
if name not in products:
print("商品不存在")
else:
# 将编辑好的商品内容写入的字典中然后 在写入文件中
products[name] = {"price": float(price), "count": int(count)}
op_file(content=products)
print("修改成功")
# 查找商品
def search():
search_name=input("请输入要查找内容:").strip()
if not search_name:
print("商品名称不能为空")
else:
products = op_file()
# 如果输入的是all,那么print所有商品的信息
if search_name =="all":
print(products)
elif search_name not in products:
print("商品不存在")
else:
print(products[search_name])
# 删除商品
def delete():
delete_name=input("请输入要删除商品名称:").strip()
if not delete_name:
print("商品名称不能为空")
else:
products = op_file()
if delete_name not in products:
print("商品不存在")
else:
# 删除指定商品
products.pop(delete_name)
# 删除后的字典重新写入
op_file(content=products)
print("删除成功")

# 调用函数 choice = input("请输入你的选择:1、 查询商品 2新增产品 3修改商品新 4、删除商品 5、退出")
def start():
func_map={"1":search,"2":add,"3":update,"4":delete,"5":quit}
while True:
choice = input("请输入你的选择:1、查询商品 2、新增产品 3、修改商品新 4、删除商品 5、退出")
if choice in func_map:
func_map[choice]()
else:
print("操作不存在")
start()

三、内置函数

3.1sum,max,min,round:

sum,max,min:真对元组或者list

1.sum():求和

l=[1,2,3,333,434]
print(sum(l))
结果:773

2.max():求最大值

l=[1,2,3,333,434]
print(max(l))
结果:434

3.min():求最小值

l=[1,2,3,333,434]
print(min(l))
结果:1

4.round():四舍五入:

例:求平均数:

avg=sum(l)/len(l)
print(round(avg,2)) # 保留小数 2是小数格式 类型不变

3.2any,all

1.any():只要list里面有一个为true,结果就位true

print(any([False,False,False,True,[]]))
结果:True

2.all():list全部为true,结果才是true

print(all([True,True,True,True,[False]]))
结果:True

3.3阿克斯码转化

1.chr():把阿克斯码转化为对应的值

 print(chr(65)) 结果:A

2.ord():把值转化为阿克斯码、

print(ord("A"))结果:65

3.阿克斯码对应表表:

https://www.cnblogs.com/biaochen/p/11307382.html

3.4十进制二进制转化

bin():十进制转化为二进制

print(bin(10)) 结果:1010 不需要看0b

int():二进制转化为十进制

print(int('1010',base=2))   #2进制转化为10进制 2代表当前为2进制数字
 print(int('a',base=16))  # 16进制转10进制

oct()10进制转化为8机制

print(oct(10))

hex():10进制转化为16进制

print(hex(10))

3.5divmod():取商和余数

print(divmod(10,3)) # 取商和余的 (3, 1)

3.6局部变量,全局变量

1.locals():取当前函数的局部变量,返回值为字典

2.global():取全局变量,返回值为字典

name="abc"
def test():
age=19
addr="北京"
print(locals()) #{'age': 19, 'addr': '北京'}
print(globals())
test()

3.7zip()压缩:

1.实现list合并,对应下标

usernames=["admin","test","dev"]
passwords=['123','456',"678"]
print(list(zip(usernames,passwords)))
结果:[('admin', '123'), ('test', '456'), ('dev', '678')]

3.8排序:sorted():结果为list

1.字符串:

s='12345612'
print(sorted(s))
结果:['1', '1', '2', '2', '3', '4', '5', '6']
print("".join(sorted(s))) # 排序后转化为字符串,使用str方法 会将中括号也转 化

2.对字典按照value进行排序:

(1)排序key:、

dic={"admin":89,"test":100,"dev":77}
print(sorted(dic)) # 按照key排序

(2)对字典按照value进行排序:

dic={"admin":89,"test":100,"dev":77}
def x(l):
return l[1]
print(sorted(dic.items(),key=x,reverse=True)) # key为sorted固定的, key赋值函数名 不需要加括号 reverse=True 降序
结果:[('test', 100), ('admin', 89), ('dev', 77)]

或者使用匿名函数:
print(sorted(dic.items(),key=lambda x :x[1],reverse=True))

(3)匿名函数:lambda:只能定义一些简单功能

name=lambda x:x*3 # 冒号前面数入参 冒号后面是返回值
print(name(5))
name=lambda x:x*3 # 冒号前面数入参 冒号后面是返回值

3.9循环调用

1.map():循环调用函数,保存到一个list里面,返回结果就是一个list

l=[1,2,3,14,906]
def t(x):
x=str(x)
if len(x)==1:
return "00"+x
elif len(x)==2:
return "0"+x
return str(x)
print(list(map(t,l)))
结果:['001', '002', '003', '014', '906']
或者使用匿名函数或者内置函数:
print(list(map(lambda x:str(x),l)))
print(list(map(str,l)))# str本身是一个函数 所有可以直接使用str函数

2.filter()循环调用函数,结果为true就保留,false就过滤掉

l = [1, 2, 3, 14, 906]
def func(x):
return x%2==0
print(list(filter(func,l))) #[2, 14, 906]
结果:[2, 14, 906]
如果使用map
print(list(map(func,l))) 
结果:
[False, True, False, True, True]

四、模块

4.1模块介绍

1.定义:一个python就是一个模块

2.模块分类:

(1)标准模块:python自带的,不需要安装,可以直接引用

(2)自定义模块:自己写的python文件

(2)第三方模块:需要安装才能使用

3.模块导入:

(1)导入实质:就是将python文件中的代码从头到尾执行一遍

如果调用函数不想被执行,使用 if __name__=="__main__":

if __name__ == '__main__':  # 他人调用时 不会执行改部分之下的内容

(2)查找模块的顺序:先从当前模块找,再从环境变量里面找

添加环境变量:

import sys
sys.path.append(r"D:\李兴培\besttest测试\测开代码\day4作业") # 将day4加入到环境变量里面
import m3
print(m3.money) 结果:5000

注:m3代码为:
print(m3.money)

4.导入文件夹:实际上是执行了文件夹下的init文件

(1)导入文件夹时,需要保证文件夹下有init文件,并且在init中引用了对应的python文件

import tools2  # 执行了init
# 直接引用文件夹
print(tools2.m5.addr) # 要在init文件里面引入m5

init中:from . import m5 # 点代表当前目录

(2)直接导入文件夹中的文件

from tools2 import m5
print(m5.addr)

5.导入方式:

(1)导入整个文件:

import m1

(2)导入指定的变量

from m1 import age,name ,op_file,op_mysql# 不需要用点

(3)*号方式 不推荐使用

from  m1 import *

4.2 os模块

1.rename,remove,rmdir,mkdir,makedirs

(1)os.rename()#重命名

os.rename("m1.py","M1.py") # 重命名 m1.py重命名为M1.py

(2)os.remove()# 删除文件,不能删除文件夹

os.remove("m2.py") # 删除文件,不能删除文件夹

(3)os.rmdir():删除空文件

os.rmdir('cars/bmw')

(4)创建文件

os.mkdir():父级目录不存在时不能创建

 os.mkdir('test')

os.makedirs():父级目录不存在时会创建父级目录

os.makedirs("cars/bmw")

2.listdir,sep,system,popen,environ,name,getcwd,chdir

(1)os.listdir():获取某个目录下内容

print(os.listdir()) # 不传参数默认获取当前目录下文件
print(os.listdir(r"D:\李兴培\besttest测试")) # 获取指定目录下的内容:绝对路径
print(os.listdir(r"../day4"))  # 一个点代表当前目录 两个点代表上一级目录

(2)os.sep():获取当前系统分隔符

print(os.sep) #\

(3)os.system():执行操作系统命令

command="ipconfig"
# 会乱吗
res=os.system(command) # 只能执行命令,返回命名是否执行成功
print(res) #0:成功 其他:失败

(4)os.popen()# 执行操作系统命令 返回结果,不会乱码

#  执行操作系统命令,可以获取到结果 所以打印不会乱码
res=os.popen(command).read()
print(res)

(5)os.environ:获取环境变量

print(os.environ) # 获取系统环境变量

(6)os.name:获取当前操作系统名称

print(os.name) # 当前从操作系统名称  nt

(7)os.getcwd():获取当前绝对路径

print(os.getcwd() )# 获取当前决对路径:D:\李兴培\besttest测试\测开代码\day5

(8)os.chdir():进入到某个目录

 os.chdir('../day4') # 进入到day4目录

3.os.walk():获取某个目录下所有内容:当前目录,当前目录下的文件夹,当前目录下的文件:

4.os.path相关

(1)isfile,isdir,exists,

os.path.isfile():判断是否为文件

print(os.path.isfile('tools'))

os.path.isdir():判断是否为文件夹

print(os.path.isdir('m2.py'))

os.path.exists():判断是否存在

print(os.path.exists('a.txt'))

(2)getsize,abspath,dirname

os.path.getsize():获取文件大小,返回字节大小

print(os.path.getsize('m2.py'))
1024b=1kb,1024b=1mb,1024mb=1g 1024g=1t

os.path.abspath():获取某个文件的绝对路径

print(os.path.abspath('m2.py')) 结果:D:\李兴培\besttest测试\测开代码\day5\m2.py
# __file__ 当前文件
# print(os.path.abspath(__file__)) # 获取当前文件的决定路径
结果:D:\李兴培\besttest测试\测开代码\day5\04常用模块.py

os.path.dirname():获取父级目录

p=r"D:\李兴培\besttest测试\测开代码\day5"
print(os.path.dirname(p))
结果:D:\李兴培\besttest测试\测开代码

(3)getctime,getatime,getmtime:返回都是时间戳

os.path.getctime():获取文件创建时间

print(os.path.getctime('m2.py')) # 获取文件创建时间  
结果:1621059414.377794

os.path.getatime():获取文件最后一次访问时间

print(os.path.getatime('m2.py')) #获取文件最后一次访问时间
结果:1621296817.1284304

os.path.getmtime():获取文件最后一次编辑时间

print(os.path.getmtime('m2.py'))
结果:1621296817.1284304

(4)join,split,walk

os.path.join():路径拼接

print(os.path.join('e:','moives','sdyjq.mp4'))  #e:moives\sdyjq.mp4

os.path.split():路径分割

p="e:/moives/sdyjq.mp4"
print(os.path.split(p))# ('e:/moives', 'sdyjq.mp4')

5.文件练习:模糊查找文件

import os
def search_file(path,keyword):
for cur_path,dirs,files in os.walk(path):
for file_name in files:
if file_name.endswith(keyword):
abs_path=os.path.join(cur_path,file_name)
print("查找到%s是,绝对路径是%s" %(file_name,abs_path))
search_file('/','.mp4')

4.3random模块

1.产生随机数字

random.randint()

print(random.randint(10000,999999))

2,产生随机小数

random.uniform()

print(random.uniform(1,99))

3.随机选择一个

random.choice()

a="1223456"
print(random.choice(a))

4.随机选择多个

random.sample()

print(random.sample(a,2)) # 2代表选择个数

5.洗牌,没有返回值,会改变原来的值

random.shuffle()

l=[1,2,4,5,10,20,3]
random.shuffle(l)
print(l) #[5, 1, 10, 20, 4, 2, 3]

4.4时间模块

4.1时间格式

1.时间戳:从计算机诞生到现在过去了多少秒

2.格式化好的时间:2021-05-12 16:59:59

4.2获取时间戳

time.time()

print(int(time.time()))

4.3获取格式化时间

time.strftime("格式")

print(time.strftime("%Y-%m-%d %H:%M:%S"))  #%Y 2021年份写全
 print(time.strftime("%y-%m-%d %H:%M:%S")) #%y:年份后两位

4.4时间戳与格式化时间相互转化:

1、时间元组

(1)时间戳转化为时间元组

标准时区:time.gmtime(时间戳)

time_tuple=time.gmtime(1621069593)

  当地时区:time.localtime(时间戳)

time_tuple=time.localtime(1621069593)

(2)格式化时间转化为时间元组

time.strptime("格式化好的时间","时间格式")

time_tuple=time.strptime('2021-05-15 17:06:33','%Y-%m-%d %H:%M:%S')

  

2.时间戳转化为格式化时间:time.strftime(格式,时间元组)

time_tuple=time.localtime(1621069593) 
print(time.strftime("%Y-%m-%d %H:%M:%S",time_tuple))
函数写法:
# 时间戳转化为格式化好的时间
def time_to_str(timestame=None,format="%Y-%m-%d %H:%M:%S"):
'''
:param timestame: 时间戳
:param format: 时间格式 %Y-%m-%d %H:%M:%S
:return: 返回的是格式化好的时间,如果不传时间戳,那么返回当前的时间
'''
if timestame:
time_tuple=time.localtime(timestame)
return time.strftime(format,time_tuple)
return time.strftime(format)
time_to_str(timestame=1621069593)

3.格式化好的时间转化为时间戳:tiime.mktime(时间元组)

print(int(time.mktime(time_tuple)))

函数写法:
# 格式好的时间转化为时间戳
def str_to_timestmap(s=None,format="%Y-%m-%d %H:%M:%S"):
'''
:param s: 格式化好的时间,比如2021-05-15 17:19:04
:param format: 时间格式
:return: 返回一个时间戳,如果不传是默认返回当前时间戳
'''
if s:
time_tuple=time.strptime(s,format)
return int(time.mktime(time_tuple))
return int(time.time())

 

 

 

posted on 2021-05-18 11:51  pei_blog  阅读(193)  评论(0)    收藏  举报