1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:SKING 4 5 """ 6 题目:购物车 7 1.启动程序后,让用户输入工资,然后打印商品列表。 8 2.允许用户根据商品编号购买商品。 9 3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒。10 4.可随时退出,退出时,打印已购买商品和余额。11 12 """13 14 import sys, os, time, string15 16 def commodity_list():17 """打印商品列表"""18 with open('commodity_list.txt', 'r') as file_commodity_list: # 打开商品列表文件commodity_list.txt19 for commodity_list in file_commodity_list:20 # 处理商品列表,并分别将序号、商品名称、商品价格、数量赋值给变量(serial_num, commdity_name, commodity_price, commdity_num)21 (serial_num, commdity_name, commodity_price, commdity_num) = commodity_list.strip().split('\t')22 dict_commodity_list.update({serial_num: (commdity_name, commodity_price, commdity_num)}) # 将商品列表存在字典里23 # 打印商品列表24 print(f'{serial_num.ljust(5)}\t{commdity_name.ljust(20)}\t{commodity_price.ljust(8)}\t{commdity_num.ljust(5)}')25 return dict_commodity_list26 27 28 count = 0 #记录用户输入工资的次数29 dict_commodity_list = {} #存放商品列表的字典30 count_buy = 0 # 统计已买的商品数量31 price_buy = 0 # 统计已买的商品总价32 33 serial_num_count = [] # 存放已购商品的序号,也就是字典dict_commodity_list的key34 buy_num = 0 #结算的时候打印已购商品的序列号35 36 37 while count<5:38 count += 139 if count == 5: #如果用户输入次数超过5次,就提示休息5s40 print('You have input too many times!')41 print('Please wait 5s...')42 for a in range(5,1,-1):43 print(f'{a}s...')44 time.sleep(1)45 count = 046 47 salary = input('Please enter your salary:') #提示让让用户输入工资48 if salary.isdigit(): #判断输入是否是数字49 commodity_list()50 Salary_balance = salary # 统计剩余的工资51 52 else:53 print('\n\nEnter wrong!try again!')54 continue55 56 while True:57 #os.system('cls') # 清屏58 print('Press "O" to settle accounts!')59 commdity_serial_num = input('Enter the serial number("Q" to exit):') # 提示让用户输入想要购买的商品序号60 61 if commdity_serial_num in dict_commodity_list.keys(): #判断输入是否是商品的列表序号62 Salary_balance = 063 dict_commodity_list = commodity_list()64 price_buy = price_buy + float(dict_commodity_list[commdity_serial_num][1]) # 已购商品价格总额65 count_buy += 1 #统计已买商品数量66 Salary_balance = int(salary) - price_buy #工资余额67 serial_num_count.append(commdity_serial_num) #统计已购商品的序号,也就是字典dict_commodity_list的key68 commodity_list()69 print(f'Have buy commodities:{count_buy},\tSalary balance:{Salary_balance}\n\n')70 71 else:72 if commdity_serial_num == 'O' or commdity_serial_num == 'o':73 #结算,显示已购商品、总价,剩余工资等信息74 #os.system('cls') # 清屏75 print('\nHave buy commdity list:')76 for b in serial_num_count: #打印已购商品列表77 buy_num += 178 print(f'\n{str(buy_num).ljust(5)}\t{dict_commodity_list[b][0].ljust(20)}\t{dict_commodity_list[b][1].ljust(8)}\t{dict_commodity_list[b][2].ljust(5)}\t')79 80 print(f'\nBuy commdities:{count_buy}, total price:{price_buy}\n')81 print(f'Salary balance:{Salary_balance}')82 sys.exit(0)83 elif commdity_serial_num == 'q' or commdity_serial_num == 'Q':84 sys.exit(0)85 else:86 print('\nEnter wrong!try again!')87 continue