实现了从products.csv中读取商品信息,购买后存入shopping_list.csv中。 第一次购买输入salary,以后每次购买从shopping_list.csv中获取余额。
# -*- coding: utf-8 -*-
# @author: sxq
import csv
# 读产品
with open("products.csv", "r", encoding = "utf-8") as f:
reader = csv.reader(f)
product_list = [row for row in reader]
# 读账户余额,文件最后一行
with open("shopping_list.csv", "r", encoding = "utf-8") as csvfile:
mlines = csvfile.readlines()
if not mlines:
print('Your current balance is None')
salary = input('Input your salary:')
if salary.isdigit():
salary = int(salary)
else:
salary = mlines[-1].split(',')
salary = int(salary[1])
shopping_list = [] # 购物车
print('Your current balance: {0}'.format(salary))
while salary > 0:
for index, item in enumerate(product_list):
print(index, item)
user_choice = input('选择要买的商品>>>:')
if user_choice.isdigit(): # 输入商品编号是数字
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >= 0:# 输入的数字在商品编码内
p_item = product_list[user_choice]
if int(p_item[1]) <= salary: # 买得起
shopping_list.append(p_item)
salary -= int(p_item[1])
print('Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m' % (p_item, salary))
else: # 买不起
print('\033[41;1m你的余额只剩[%s]了!\033[0m' % salary)
else: # 输入的数字不在商品编码内
print('product code [%s] is not exist!' % user_choice)
elif user_choice == 'q': # 输入退出
print('-----------------shopping list------------------')
for p in shopping_list:
print(p)
print('Your current balance:', salary)
with open("shopping_list.csv", "a", encoding="utf-8" ,newline = '') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['products', 'price'])
csv_writer.writerows(shopping_list)
csv_writer.writerow(['current balance',salary])
exit()
else: # 输入无效字符
print('invalid option')
第一次购买:
Your current balance is None
Input your salary:10000
Your current balance: 10000
0 ['IphoneX', '8800']
1 ['Mac Pro', '9800']
2 ['Bick', '800']
3 ['Watch', '10600']
4 ['KFC', '31']
5 ['Book', '20']
选择要买的商品>>>:0
Added ['IphoneX', '8800'] into shopping cart, your current balance is 1200
0 ['IphoneX', '8800']
1 ['Mac Pro', '9800']
2 ['Bick', '800']
3 ['Watch', '10600']
4 ['KFC', '31']
5 ['Book', '20']
选择要买的商品>>>:2
Added ['Bick', '800'] into shopping cart, your current balance is 400
0 ['IphoneX', '8800']
1 ['Mac Pro', '9800']
2 ['Bick', '800']
3 ['Watch', '10600']
4 ['KFC', '31']
5 ['Book', '20']
选择要买的商品>>>:q
-----------------shopping list------------------
['IphoneX', '8800']
['Bick', '800']
Your current balance: 400
继续购买:
Your current balance: 400
0 ['IphoneX', '8800']
1 ['Mac Pro', '9800']
2 ['Bick', '800']
3 ['Watch', '10600']
4 ['KFC', '31']
5 ['Book', '20']
选择要买的商品>>>:4
Added ['KFC', '31'] into shopping cart, your current balance is 369
0 ['IphoneX', '8800']
1 ['Mac Pro', '9800']
2 ['Bick', '800']
3 ['Watch', '10600']
4 ['KFC', '31']
5 ['Book', '20']
选择要买的商品>>>:q
-----------------shopping list------------------
['KFC', '31']
Your current balance: 369