'''4.要求用户输入总资产,例如:2000 显示商品列表,让用户根据序号选择商品,加入购物车 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。 附加:可充值、某商品移除购物车''' # 变量的含义: # sum是累计金额,car是购物车,asset是资产,balance是余额,choose是选择的商品编号, # num是移除的商品数量 def fun1(dic): print(dic) sum = 0 car = {} asset = int(input('Please enter your asset:')) balance = asset while True: while True: choose = int(input('Please choose the number that you want to buy:')) goods = dic[choose] if(car.__contains__(choose)): car[choose] = [goods[0],goods[1],car[choose][2] + 1] else: car[choose] = [goods[0], goods[1], 1] print(car) sum += goods[1] balance -= goods[1] print('The remaining amount is {}'.format(balance)) isexit = input('Do you continue to buy?(Y/N) ').lower() if isexit == 'y': continue elif isexit == 'n': break else: print('Invalid input!') while True: if sum == 0: print('The shopping cart is empty! ') break elif asset > sum: print('Purchase success!') sum = 0 asset = balance car = {} break else: re = input('Your balance isn\'t enough!Select (remove) some of goods or (recharge):') if re == 'remove': regoods = int(input('Please choose the number that you want to remove:')) num = int(input('Please enter the number of removeing:')) if (car.__contains__(regoods)): if num <= car[regoods][2]: sum -= car[regoods][1] * num balance += car[regoods][1] * num car[regoods][2] -= num if num == car[regoods][2]: del car[regoods] print("累计购买金额{},购物车{},余额{}".format(sum, car, balance)) else: print('移除数量超出范围!') else: print("The shopping cart don't have this goods!") if re == 'recharge': money = int(input('Please enter the amount of recharge:')) asset += money balance += money print('The remaining amount is {}'.format(balance)) dic1 = {1:['荔枝',666],2:['牛油果',888],3:['奇异果',686],4:['榴莲',868]} fun1(dic1)