这算是我第一篇教程博客吧,写的不咋好,程序可能有点麻烦,有些地方应该可以优化,但目前我懂的知识只能做到这个地步,望各位大谅解

写了40分钟,有可以优化的地方希望各位指点指点。好了,开始正题

一个普通的购物车程序。

要求:1将商品数据存储在文件里(这里我设置的是commodity.txt)

   2将用户购买的商品,剩余金额存入文件(这里我设置的是文件user.txt)

#Auther:He Jianhan
#购物车优化程序
buy =[]
c = []
already =[]
with open("user.txt") as users:
user = users.readlines()#导入user文件,并将其存入列表
if user:#当user列表有数据的时候,执行改命令
for foruser in user:
forusers = foruser.strip()
buy.append(forusers)
money = buy[0]
print("你还有\033[31;1m%s\033[0m钱" % (money))#显示你之前的余额
del buy[0]
if buy:#如果之前有购买商品,则显示您之前购买过什么
print("您之前购买了")
for buys in buy:
print(buys)
else:#如果之前没有定义过金额,则需要输入
money = input("你的金额;")
if money.isdigit():#判断输入的金额是否是整数
money = int(money)
with open("commodity.txt") as commodity:#导出商品的数据存入列表,以便之后显示
com = commodity.readlines()
for a in com:
b = a.strip().split(",")
c.append(b)
while True:
for number,lists in enumerate(c):#打印商品以供用户选择
print(number,lists)
choice = input("选择哪件商品")
if choice.isdigit():#判断输入的是否是整数
choice = int(choice)
if -1 < choice <len(c):#确定输入的数字是否有对应的商品
price = int(c[choice][1])
if money >= price:#判断金额是否购买想购买的商品
money -= price
print("你购买了\033[31;1m%s\033[0m"
"剩下\033[41;1m%s\033[0m钱"%(c[choice][0],money))
already.append(c[choice][0])
else:
print("穷鬼,买什么买")
else:
print("没有这个商品")
elif choice == "q":#选择商品时选择q择退出循环
money = str(money)
print("你还剩下{0}".format(money))#显示剩下多少钱
buy.insert(0,money)
print("你这次总共买了:\n====>")
for alreadys in already:
buy.append(alreadys)
print(alreadys)
with open("user.txt","w") as users:#将列表中的数据覆盖到原文件
for buyalready in buy:
users.write(buyalready+"\n")
break
else:
print("没有这个命令")
else:
print("输入错误")
posted on 2017-07-14 21:02  Gavinn  阅读(216)  评论(1编辑  收藏  举报