day2:作业 购物车程序及升级版本

#  要求:
# 1.启动程序后让用户输入工资然后打印商品列表
# 2.允许用户根据商品编号购买商品
# 3.用户选择商品后,检测余额是否足够,够就直接扣款,不够就提醒
# 4.可随时退出,退出时打印已购买商品和余额
thing = [('iphone',4888),('MP3',2888),('Book',88),('apple',6),('Ipad',1888)]
basket = []
salary = input('please input your salary:')
if salary.isdigit():
    salary = int(salary)
while True:
    for index,item in enumerate(thing):
        print(index,item)
    chose = input('请输入你想要购买的商品序号:')
    if chose.isdigit():
        chose = int(chose)
        if  0 <= chose < len(thing):
            if thing[chose][1] < salary:
                basket.append(thing[chose])
                salary = salary - thing[chose][1]
                print('你已经购买了 %s ,您的余额为\033[31;1m%s\033[0m'%(thing[chose],salary))
            else:
                print('你的余额不足!')
        else:
            print('商品序号不存在!')
    elif chose == 'q':
        print('您已购买的商品如下:')
        for i in basket:
            print(i)
        print('您的余额为:', salary)
        exit()
    else:
        print('请重新输入!')
#购物车升级版
#用户入口:1.商品信息存在文件里
list1 = []
list2 = []
f = open('menu2')
for i in f:
    i2 = i.strip('\n')
    i3 = i2.split(',')
    i4 = (i3[0],int(i3[1]))
    list1.append(i4)
f.close()
salary = input('请输入你的工资:')
if salary.isdigit():
    salary = int(salary)
while True:
    for k,s in enumerate(list1):
        print(k,s)
    choice = input('请输入您要选择的商品序号:')
    if choice.isdigit():
        choice = int(choice)
        if 0 <= choice <= len(list1):
            if  list1[choice][1] < salary:
                list2.append(list1[choice])
                salary = salary - list1[choice][1]
                print('您已经购买了%s,您的余额为%s'%(list1[choice],salary))
            else:
                print('您的余额已不足!')
        else:
            print('您输入的序号不存在!')
    elif choice == 'q':
        print('您已购买的商品如下:')
        for t in list2:
            print(t)
        print('您余额为:',salary)
        exit()
    else:
        print('您的输入有误,请重新人输入!')
#此为商家版入口
#要求:1..可以修改商品价格
list1 = []
f = open('menu2','r+')
print('--------------------------------------------------------')
for i,s in enumerate(f):
    s1 = s.strip('\n')
    s2 = s1.split(',')
    list1.append(s2)
    print(i,s2)
print('---------------------------------------------------------')
f.close()
while True:
    f1 = open('menu2','r+')
    revision = input('请输入你要修改的商品的序号:')
    if revision == 'q':
        exit()
    price = input('请输入修改后的价格:')
    list1[int(revision)][1] = str(price)
    for k in list1:
        k1 = ','.join(k)
        print(k1)
        f1.write(k1+'\n')
    f1.close()
#此为商家版入口
#要求:可以在文件里添加商品及价格
list1 = []
while True:
    name = input('请输入你要添加的商品名称:')
    price =input('请输入商品的价格:')
    if name == 'q':
        exit()
    else:
        f = open('menu2','a+')
        for i in f :
            i1 = i.strip('\n')
            i2 = i1.split(',')
        list1 =[name,price]
        g = ','.join(list1)
        f.write(g+'\n')
        f.close()

 

 

posted on 2017-08-23 10:24  一支Liqun  阅读(75)  评论(0)    收藏  举报

导航