python 购物车程序_Python 购物车程序(文件版)

'''

购物车程序

用户入口:

1.商品信息存在文件里

2.已购商品,余额记录

商家入口:

1.可以添加商品,修改商品价格

'''

filePath = "D:\Python_work\Lpython\day2\shoppinglist.txt"

with open (filePath, "r") as f:

filetext = f.readlines()

k = len(filetext)

# print(filetext)

# 提取商品列表(将字符串以逗号分割写入列表)

fileList = []

for i in range(k):

c = filetext[i].split(",")

fileList.append([c[0],int(c[1])])

print(fileList)

# ================

# 用户入口

# ================

fileLen = len(fileList)

salary = int(input("请输入您的工资: "))

for j in range(fileLen):

# 打印商品(编号,商品名称,价格)

print(j, '.', fileList[j][0], ' ', fileList[j][1])

shoppingList = []

while True:

selectNum = input("请选择商品编号:")

if selectNum.isdigit():

selectNum = int(selectNum)

if 0 <= selectNum < fileLen:

p_item = fileList[selectNum]

if p_item[1] <= salary:

shoppingList.append(p_item)

salary -= p_item[1]

print("已添加 %s 商品到购物车,您的余额为:\033[31;0m %s \033[0m" % (p_item, salary))

else:

print("\033[41;1m你的余额只剩[%s]啦,还买个毛线啊 \033[0m" % salary)

for going in shoppingList:

print("您已购商品为: ", going)

print("您当前的余额为: ", salary)

break

else:

print("您选择的 [%s] 不存在,请重新选择 " % selectNum)

elif selectNum == "q":

print("---------shopping list---------")

for going in shoppingList:

print("您已购商品为: ", going)

print("您当前的余额为: ", salary)

exit()

else:

print("无效选项")

# ================

# 商家入口

# ================

goodskey = dict(fileList)

print(goodskey)

# 修改商品名称 & 修改价格 & 添加商品

goodskey["Iphone11"] = "5999"

goodskey.update({'Iphone12':goodskey.pop("Iphone11")})

print(goodskey)

with open(filePath, 'w+') as f:

for key in goodskey: # for key,value in goodskey.items(): 不建议这样写

f.write('{0},{1}\n'.format(key,goodskey[key]))

# 添加商品

with open (filePath, "a+") as f:

f.write("Python8,8800\n")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值