購物車程序:
需求:
1. 啟動程序,讓用戶輸入工資,然后打印商品列表;
2.允許用戶根據商品編號或者商品名字購買商品;
3.用戶輸入商品列表后檢測余額是否足夠,夠就直接扣款,不夠就提醒;
4.用戶可以一直購買商品,也可以直接退出,退出后打印已購買商品和余額;
-
balance=0 shoplist=[{'identifier':1,'apple':5},{'identifier':2,'banana':4},{'identifier':3,'cake':20},{'identifier':4,'shoe':99},{'identifier':5,'diamond':200}] shoplist1,shoplist2,shoplist3=[],[],[] shop_cart={} for i in shoplist: k=i del k['identifier'] shoplist1.append(k)#提取出商品名稱和單價 shoplist2.append(list(k.keys())[0])#單獨提取出商品名稱 shoplist3.append(list(k.values())[0])#單獨提取出商品單價 salary=int(input('please input your salary:')) print("the selective menu are as follwed:") print(shoplist) print('please select your want goods:') while 1: want=input() #可以輸入商品的數字編號或者商品名字 if want.isdigit() and int(want) in range(1,len(shoplist)+1): want=int(want) goods=shoplist2[want - 1] price=shoplist3[want - 1] elif want in shoplist2: p = shoplist2.index(want) goods=want price=shoplist3[p] else: print("the goods is not existed, please input again") continue print('you has selected:',goods, ',its price:', price) quantity = int(input('please input the quantity of the goods:')) if salary>=quantity*price: salary-=quantity*price balance+=quantity*price shop_cart[goods]={price:quantity} else: print('sorry,you can not afford it') print("you can input any word to keep shopping or input 'N'to end shopping") s=input() if s!='N': continue else: break print('your shoppinglist is as follows:') print(shop_cart) print('your shopping consuption is:',balance)
編譯結果如下:
your shoppinglist is as follows: {'diamond': {200: 10}, 'apple': {5: 10}} your shopping consuption is: 2050