深夜十点半(三)——我的第三个Python程序“增强版购物车”

项目要求:

1、增强版购物车是利用了文件系统,保存用户的购物列表和当前余额信息,在用户每次购物前先读取用户当前余额后再进行购买,并把购买的物品名称存到列表中;

2、用文件系统保存商品明细,不用每次都进行人工输入

程序要点:

1、文件读写操作

2、把一个格式化的文件内容读取到列表中,并对不需要的\n等信息进行处理,得到有效的格式化数据

待改进:

程序结构化不够,比较乱,后面可以函数化进行封装

'''用户入口:
1、商品信息存在文件里
2、已购商品,余额记录
商家入口:
1、可以添加商品,修改商品价格
'''
# 用户入口:
# 从文件中读取所有商品信息到字典中

f_product_list = open(r"C:\Users\Administrator\PycharmProjects\S14Week2\product", 'r')
f_shopping_list = open(r"C:\Users\Administrator\PycharmProjects\S14Week2\shoppinglist", 'r+')
product_list = []
shopping_list = []
length = 0
while True:
product_list_temp = f_product_list.readline()
# product_list_temp.strip()
if product_list_temp == "" or product_list_temp == "\n":
break
# print("RAW Line is :",product_list_temp)
product_list_temp = product_list_temp.strip()
# print("Strip result is :", product_list_temp)
product_list_temp = product_list_temp.split(",")
# print("Split result is :",product_list_temp)
# product_list_temp = product_list_temp.strip()
# print(product_list_temp)
product_list.append(product_list_temp)
# print("Final result is :",product_list)
product_list = list(product_list)
salary = 0
while True:
shopping_list_temp = f_shopping_list.readline()
if shopping_list_temp == "" or shopping_list_temp == "\n":
break
# print("RAW Line is :",product_list_temp)
shopping_list_temp = shopping_list_temp.strip()
# print("Strip result is :", product_list_temp)
shopping_list_temp = shopping_list_temp.split(",")
# print("Split result is :",product_list_temp)
# product_list_temp = product_list_temp.strip()
# print(product_list_temp)
shopping_list.append(shopping_list_temp)
salary = int(shopping_list_temp[1])

shopping_list = list(shopping_list)
# print("Final result is :",product_list)
print("Notice, this is salary:",salary)
product_list = list(product_list)
if salary == None:
salary = input("Input your salary:")
if salary.isdigit():
salary = int(salary)

while True:
for index, item in enumerate(product_list):
print(index, item)
choice = input("Input your choice:")
if choice.isdigit():
choice = int(choice)
if choice < len(product_list) and choice >= 0:
p_item = product_list[choice]
print(p_item)
if int(p_item[1]) <= salary: # 买得起
shopping_list.append(p_item)
salary -= int(p_item[1])
f_shopping_list.write(p_item[0])
f_shopping_list.write(",")
f_shopping_list.write(str(salary))
f_shopping_list.write("\n")
print("Added %s into shoppint cart, your current balance is %s" % (p_item, salary))
else:
print("Sorry, your money is not enough!")
else:
print("Product is not exist")
elif choice == 'q':
print("Your current balance is ", salary)
f_shopping_list.close()
f_product_list.close()
break

猜你喜欢

转载自www.cnblogs.com/huaweifisher/p/9460298.html