python购物车结算_python学习--购物车4

该博客介绍了一个Python实现的购物车结算系统,包括用户登录、账号锁定机制、购物车计算和购物历史记录等功能。系统读取并处理字典列表,用户通过输入选择商品并进行结算,同时支持账号充值和查看购物历史。
摘要由CSDN通过智能技术生成

defreadDirInfo(filename):'读取字典列表,依据传递的文件名,获取不同的字典信息'nameList= ''with open(filename,'a+', encoding='utf8') as f:

f.seek(0)

nameList=str(f.readlines())

nameList= nameList.strip(']').strip('[')

nameList= nameList.strip('\"').strip('\"')if len(nameList) ==0:return{}return eval(nameList) #字符转字典

def login(iTime = 3):'用户登录操作,包括以下功能:1、判断是否为注册账户;\

2、登录账户是否被锁定(注:默认输错用户名密码三次后,锁定账号,五分钟内不能登录)'i= 1flag=False

lock_namelist= readDirInfo('locklist.txt')while i <=iTime:

username= input("username:")

password= input("password:")ifloginLock(username,lock_namelist):print("you username is locked, try again after 5 min")break

eliflogincheck(username,password):print("welecom to shopping maket")

flag=Truebreak

elif i ==iTime:print("input more than three times, try again after 5 min")

addLockDir(username, lock_namelist)break

else:print("you put an wrong name or password,please input again")

i+= 1

returnflag,usernamedefloginLock(name, lock_namelist):'判断登录账号是否被锁定,如果被锁定时间超过5分钟,允许用户再次登录'flag=Falseif name inlock_namelist:

last_time= datetime.datetime.strptime(lock_namelist[name], "%Y-%m-%d %H:%M:%S")

now_time=datetime.datetime.now()

minute= (now_time -last_time)if int(minute.seconds/60) <= 5:

flag=Truereturnflagdeflogincheck(name,password):'是否为注册账号'flag=False

name_dir= readDirInfo('name.txt')if name inname_dir:if password ==name_dir[name]:

flag=TruereturnflagdefaddLockDir(name,lock_namelist):'字典中添加元素,如果元素存在,修改元素的值'

if name inlock_namelist:

lock_namelist[name]= datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")else:

lock_namelist[name]= datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")

with open('locklist.txt', 'w', encoding="utf8") as f_read:

f_read.write(str(lock_namelist))defPrintOper():'打印操作说明'prolist= '''*************** 系统操作说明 ****************

q : 退出系统

c : 账号充值

h : 购物记录

l : 商品列表

************************************************'''

print(prolist)defCreateDir():'判断文件夹是否存在,如果存在则退出,如果不存在,创建文件夹'isExists= os.path.exists('History')if notisExists:

os.mkdir('History')returnisExistsdefExit():'退出购物系统,退出时进行购物结算'Account()

saveLevelMoney()

exit()defsaveLevelMoney():

with open('remain.txt','w',encoding='utf8') as f:

f.write(str(remain_dir))defAccount():'购物计算,将购物信息写入购物历史文件中'

if len(shopping_cart) ==0:returnFalseprint("\033[34;1m---------------product list-----------------\033[0m \n \033[42;1m")

temp= 'id product number pric Totalpric'

print(temp)

index= 1total_mon=0

f= open("product.txt", "a+", encoding="utf8")

now_time= datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]')

f.write(now_time+ '\n' + temp + '\n')

temp= ''

for i inshopping_cart.keys():

total_mon+= shopping_cart[i][1] *shopping_cart[i][0]

temp= str("%d %10s %7d %7d %7d \n" % (index, i, shopping_cart[i][1], shopping_cart[i][0],

shopping_cart[i][1] *shopping_cart[i][0]))print(temp)

f.write(temp)

index+= 1f.close()print("you pay money is:%d \n you level money is: %d \n" %(total_mon, remain_dir[name]))print("\033[0m \n \033[34;1m-------------end-------------\033[0m")defRecharge():'账号充值操作'

whileTrue:

temp= input("Please rechange money:")iftemp.isdigit():if name inremain_dir:

remain_dir[name]+=int(temp)else:

remain_dir[name]=int(temp)break

print("you input a unknow number,please check it and input again!")defHistory():'打印历史购物记录'filename= 'History\\' + name + '.txt'filename= filename.rstrip("\\")print(filename)ifos.path.exists(filename):

with open(filename,'r',encoding='utf8') as f:for line inf:print(line.strip('\n'))else:print('No you shoppong history')defOperation():'用户交互操作'

whileTrue:

PrintOper()

oper= str(input("Please input you choice:")).strip()if oper == 'l':print('欢迎进入购物中心')

shopping(product_list)elif oper inOper_dir:

Oper_dir[oper]()else:print("You input no in Oper list!")continue

defProductList(print_list):'打印商品列表'

if isinstance(print_list, dict): #是否为列表

for key inprint_list:print(key)else:

index=0for product inprint_list:print(index, product)

index+= 1

print('b:','返回上级菜单')print('q:','退出购物中心')print('c','充值')defshopping(product_list):'购物操作'current_layer=product_listwhileTrue:

ProductList(current_layer)

choice= input(">>:").strip()if len(choice) == 0: continue

ifchoice.isdigit():

choice=int(choice)if choice >= 0 and choice

product=current_layer[choice]if product[1] <=remain_dir[name]:if product[0] inshopping_cart:

shopping_cart[product[0]][1] += 1

else:

shopping_cart[product[0]]= [product[1], 1]

remain_dir[name]-= product[1]print("\033[42;1mAdded product: %s into shoing cart ,you current balance %s \033[0m"

%(product[0], str(remain_dir[name])))else:print("\033[42;1m [warning] you balance is no enough\033[0m, product:" +str(

product[1]) + "short for" + str(product[1] -remain_dir[name]))else:print("\033[41;1mYou choice product is no in product_list\033[0m")elif choice incurrent_layer:if isinstance(current_layer, dict): #是否为列表

last_layer.append(current_layer)

current_layer=current_layer[choice]elif choice == 'q':break

elif choice == 'b':

current_layer=BackUpLevel(current_layer)elif choice == 'c':

Recharge(name)defBackUpLevel(current_layer):'返回到商品列表上一层'

iflast_layer:

current_layer= last_layer[-1]

last_layer.pop()returncurrent_layerimportdatetimeimportos

product_list= {"生活用品":[['毛巾',20],

['洗衣液',80],

['衣架', 10],

['洗衣粉',60],

['洗发水', 80],

['厕洗剂',50]],"家电":[['电视机',5000],

['电饭煲',300],

['电磁炉',200],

['高压锅',800],

['电饼铛',200]],

}

shopping_cart={}

Oper_dir= {'q':Exit,'c':Recharge,'h':History}

last_layer=[ product_list ]

remain_dir= readDirInfo('remain.txt')

flag,name=login()ifflag:

Operation()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值