Python 购物车程序(文件版)
'''
购物车程序
用户入口:
1.商品信息存在文件里
2.已购商品,余额记录
商家入口:
1.可以添加商品,修改商品价格
'''
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 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" ) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步