python编程 基础入门练习题二——购物车
本节内容:
购物车
用户入口
1.商品信息存在文件里
2.已购商品,余额记录,永久留存(只有第一次需要输入工资)
商家入口
1.商品信息存在文件里
2.可以添加商品,修改商品价格
购物车设计
流程图:

代码:
seller.py
#-*- coding:utf-8 -*- #Author:'Yang' exit_flag = False while not exit_flag: product_choice=input("添加新的商品请按a键,修改原有商品价格请按c键,退出请按q键\n>>:") if product_choice=='a':#添加新的商品 product_add=input("添加新的商品及价格>>:") with open('product_list.text','a') as pa: pa.write(product_add) pa.write('\n') elif product_choice=='c':#修改商品价格 product={} with open('product_list.text','r+') as pc:#将文件中的商品信息存储在字典中 for i,line in enumerate(pc): product[i]=line.strip() print(product)#修改前的价格表 price_choice=int(input("请输入修改商品的序号:")) if price_choice in range(len(product)): print("原商品及价格:",product[price_choice]) product_split=product[price_choice].split(',') price_change=input("请输入新的价格:") product_split[1]=price_change print("修改后商品及价格:",product_split[1]) with open('product_list.text','w') as pn:#将新的价格表写入文件 for j in product: if j==price_choice: product[j]="%s,%s" %(product_split[0],product_split[1]) pn.write("%s\n" %product[j]) print(product)#修改后的价格表 elif product_choice=='q':#退出程序,并列出商品清单 exit_flag = True print("product_list".center(60,"-")) with open('product_list.text','r') as pq: for n,pro_list in enumerate(pq): print(pro_list.strip())
shopping_cart.py
#-*- coding:utf-8 -*- #Author:'Yang' salary=input("请输入您的工资>>:") lists=[]#商品列表 with open("product_list.text",'r') as p:#将数据读入列表 for i,line in enumerate(p): lists.append(line.strip()) if salary.isdigit():#判断输入是否为数字 salary=int(salary) shopping_list=[] while salary>0: with open("shopping_list.text",'w') as s: user_choice=input("请输入商品编号,加入购物车>>>:") if user_choice.isdigit():#判断输入是否为数字 user_choice=int(user_choice) if user_choice in range(len(lists)): shopping_list.append(lists[user_choice]) product_name=lists[user_choice].split(',')[0] product_price=int(lists[user_choice].split(',')[1]) if salary>=product_price: salary=salary-product_price print("您已购买%s,余额为%d"%(product_name,salary)) else: print("您的余额不足!只有%s" %salary) elif user_choice=='q': print("shopping_list".center(60,'-')) for n in shopping_list: print(n) s.write(n)#将所选商品写入文件 s.write('\n') print("这是您的当前余额:%d"%salary) s.write("current balance:%s" % str(salary))#将当前余额 break else: print("输入商品编码不存在!") else: print("无效输入!")
~
浙公网安备 33010602011771号