Python实践之路3——购物车

一、代码需求:

用户入口:
  1.商品的信息存到文件里
  2.已购商品,余额记录
商家入口:
  1.可以添加商品
  2.修改商品价格
  3.存储商品列表

二、程序代码:

         功能实现:

    1、加载商品信息和用户余额信息

    2、用户界面实现购物、打印购物清单和用户余额及用户余额更新;

    3、商家界面实现商品添加、修改商品价格及商品信息更新。

    程序目录:

    其中test.py为实现过程中,部分功能的测试片段,可不予考虑。

    买家用户名和密码存在名为‘balance.txt’的文件中。

1 VisonWong:4200
2 VisonWong1:20000
3 VisonWong2:30000
4 VisonWong4:4969

    商品列表和价格存在名为‘product.txt’的文件中。

1 Iphone:5800
2 Mac Pro:9800
3 Bike:800
4 Watch:10600
5 Coffee:31
6 Beats:1200
7 books:80

        程序代码:

  1 #!/user/bin/env ptyhon
  2 # -*- coding:utf-8 -*-
  3 # Author: VisonWong
  4 
  5 
  6 import fileinput
  7 
  8 #读取商品信息
  9 product_list = []
 10 f = open("product.txt", "r")  # 打开文件
 11 for line in f.readlines():
 12     line = line.strip()  # 去掉前后的空格
 13     item, price = line.split(":")  # 以冒号分割得到前后两个数据的字符串列表,分别赋给两个变量
 14     product_list.append([item,int(price)])  # 添加数据
 15 f.close()
 16 
 17 #读取用户余额信息
 18 user_name = []
 19 user_balance = []
 20 f1 = open("balance.txt", "r")  # 打开文件
 21 for line1 in f1.readlines():
 22     line1 = line1.strip()  # 去掉前后的空格
 23     user, balance = line1.split(":")  # 以冒号分割得到前后两个数据的字符串列表,分别赋给两个变量
 24     user_name.append(user)
 25     user_balance.append(balance)
 26 f1.close()
 27 
 28 
 29 # 用户入口
 30 # 用户购物
 31 def user_shopping():
 32     Username = input("请输入你的用户名:")
 33     if Username in user_name:
 34         salary = user_balance[user_name.index(Username)] #检索用户名获得所在位置
 35         index_updata = '{}:{}'.format(Username, salary) #为后面修改文件提供索引
 36         print("你的余额还有{}元".format(salary))
 37     else:
 38         salary = input("请输入你的薪水:")
 39     for index, item in enumerate(product_list):
 40         print(index, item)
 41     if salary.isdigit(): #检测字符串是否只由数字组成
 42         salary = int(salary)
 43     shopping_list = []  # 存放用户购物车清单
 44     while True:
 45         option = input("请输入你要购买的商品标号或“quit”退出")
 46         if option.isdigit():
 47             option = int(option)
 48             if option >= 0 and option <= len(product_list):
 49                 p_item = product_list[option]  # 用户选择的商品
 50                 if salary >= p_item[1]:
 51                     shopping_list.append(p_item)
 52                     salary -= p_item[1]
 53                     print("添加{}到购物车成功,你的余额还有{}".format(p_item[0],salary))
 54                 else:
 55                     print("你的余额不足,只剩{}元".format(salary))
 56             else:
 57                 print("输入错误,请重新输入!")
 58         elif option == "quit":
 59             print("----------------购物清单---------------")
 60             for i in shopping_list:
 61                 print(i)
 62             print("你的余额为{}".format(salary))
 63             print("..........exit.........")
 64             if Username in user_name:
 65                 for line in fileinput.input('balance.txt', inplace=1):
 66                     print(line.replace(index_updata, '{}:{}'.format(Username, salary)).strip())
 67             else:
 68                 f1 = open('balance.txt', 'a')
 69                 f1.write('\n{}:{}'.format(Username, salary))
 70                 f1.close()
 71             exit()
 72         else:
 73             print("无效的输入")
 74 
 75 
 76 # 商家入口
 77 # 商家添加商品
 78 def add_product():
 79     while True:
 80         product_name = input("请输入你要添加的商品名字或'quit'退出")
 81         if product_name == 'quit':
 82             break
 83         product_price = input("请输入你要添加商品的价格:")
 84         f = open("product.txt", "a")
 85         f.write('\n{}:{}'.format(product_name, product_price))
 86         f.close()
 87         print("添加成功!")
 88 
 89 # 修改商品价格
 90 def change_price():
 91     while True:
 92         for index, item in enumerate(product_list):
 93             print(index, item)
 94         choice = input("请输入修改商品所对应的标号或输入'quit'退出")
 95         if choice.isdigit():
 96             choice = int(choice)
 97             if choice >= 0 and choice <= len(product_list):
 98                 index_updata = '{}:{}'.format(product_list[choice][0], product_list[choice][1])  # 为后面修改文件提供索引
 99                 price_change = input("请输入你要改变商品的价格:")
100                 product_list[choice][1] = price_change
101                 for line in fileinput.input("product.txt", inplace=1): # 对输入的选择行进行修改
102                     print(line.replace(index_updata, '{}:{}'.format(product_list[choice][0], price_change)).strip())
103             else:
104                 print("输入无效")
105         elif choice == "quit":
106                 break
107         else:
108             print("无效的输入")
109 
110 #主函数
111 while True:
112     print("\33[31;0m欢迎进入购物模拟程序\33[0m".center(50, "#"),
113           "\n1 买家\n"
114           "2 商户\n"
115           "q 退出程序\n")
116     Ident = input("\33[32;0m选择要进入模式的ID:\33[0m")
117     if Ident == '1':
118         user_shopping()
119         break
120     elif Ident == '2':
121         process = input("请输入相应ID:【1】添加商品  【2】修改商品价格 【q】退出")
122         if process == "1":
123             add_product()
124             break
125         elif process == "2" :
126             change_price()
127             break
128         elif process == "q":
129             break
130         else:
131             print("输入的ID无效,请重新选择")
132     elif Ident == 'q':
133         break
134     else:
135         print("33[31;0m输入的ID无效,请重新选择\33[0m")

 

       运行效果:

       买家界面:

 1 E:\Python\PythonExercising\shopping\venv\Scripts\python.exe E:/Python/PythonExercising/shopping/shopping.py
 2 ##############欢迎进入购物模拟程序############### 
 3 1 买家
 4 2 商户
 5 q 退出程序
 6 
 7 选择要进入模式的ID:1
 8 请输入你的用户名:VisonWong
 9 你的余额还有5800元
10 0 ['Iphone', 5800]
11 1 ['Mac Pro', 9800]
12 2 ['Bike', 800]
13 3 ['Watch', 10600]
14 4 ['Coffee', 40]
15 5 ['Beats', 1200]
16 6 ['books', 80]
17 请输入你要购买的商品标号或“quit”退出4
18 添加Coffee到购物车成功,你的余额还有5760
19 请输入你要购买的商品标号或“quit”退出5
20 添加Beats到购物车成功,你的余额还有4560
21 请输入你要购买的商品标号或“quit”退出quit
22 ----------------购物清单---------------
23 ['Coffee', 40]
24 ['Beats', 1200]
25 你的余额为4560
26 ..........exit.........
27 
28 Process finished with exit code 0

 

       商户界面:

 1 E:\Python\PythonExercising\shopping\venv\Scripts\python.exe E:/Python/PythonExercising/shopping/shopping.py
 2 ##############欢迎进入购物模拟程序############### 
 3 1 买家
 4 2 商户
 5 q 退出程序
 6 
 7 选择要进入模式的ID:2
 8 请输入相应ID:【1】添加商品  【2】修改商品价格 【q】退出2
 9 0 ['Iphone', 5800]
10 1 ['Mac Pro', 9800]
11 2 ['Bike', 800]
12 3 ['Watch', 10600]
13 4 ['Coffee', 31]
14 5 ['Beats', 1200]
15 6 ['books', 80]
16 请输入修改商品所对应的标号或输入'quit'退出4
17 请输入你要改变商品的价格:40
18 0 ['Iphone', 5800]
19 1 ['Mac Pro', 9800]
20 2 ['Bike', 800]
21 3 ['Watch', 10600]
22 4 ['Coffee', '40']
23 5 ['Beats', 1200]
24 6 ['books', 80]
25 请输入修改商品所对应的标号或输入'quit'退出quit
26 
27 Process finished with exit code 0

 

posted @ 2018-03-24 17:27  VisonWong  阅读(332)  评论(0编辑  收藏  举报